Java三种循环求和方法
更新时间:2018年02月26日 09:34:39 作者:彬菌
本篇文章给大家介绍了Java三种循环求和的方法,大家在学程序的时候如果能用的到,参考下吧。
注意:100之和为5050
普通for循环:
public class HundredSum {
public static void main(String[] args){
int x=0;
for(int i=1;i<=100;i++){
x=x+i;//x+=i;
}
System.out.print(x);
}
}
while循环:
public class HundredSum {
public static void main(String[] args){
int x=0; int i;
while (i<=100){
x=x+i; //x+=i;
i++;
}
System.out.print(x);
}
}
do-while循环:
public class HundredSum{
public static void main(String[] args){
int i=0,x=0;
do{
x=x+i; //x+=i;
i++;
}while (i<=100); //先循环do语句块,再执行while,不满足while条件则跳出循环
System.out.print(x);
}
}
以上就是本次整理的3种常用的求和方法,感谢大家对脚本之家的支持。
相关文章
Java中的HashMap弱引用之WeakHashMap详解
这篇文章主要介绍了Java中的HashMap弱引用之WeakHashMap详解,当内存空间不足,Java虚拟机宁愿抛出OutOfMemoryError错误,使程序异常终止,也不会靠随意回收具有强引用的对象来解决内存不足的问题,需要的朋友可以参考下2023-09-09


最新评论