黑马程序员技术交流社区
标题:
while的应用
[打印本页]
作者:
fantianfei
时间:
2015-7-2 09:31
标题:
while的应用
你的程序要读入一系列正整数数据,输入-1表示输入结束,-1本身不是输入的数据。程序输出读到的数据中的奇数和偶数的个数。输入一系列正整数,整数的范围是(0,100000)
我的思路:
1.需要两个变量来分别记录奇数和偶数的个数;2.需要用到循环来读入数据;3.根据条件限制来判断循环条件
public class Test{
public static void main(String[] args) {
//获取控制台输入
Scanner in = new Scanner(System.in);
int count1 = 0;
int count2 = 0;
int number = in.nextInt();
boolean size = true;//用来判断输入的数是否在取值范围内
while(number != -1){
if(number>0 && number<10000){
int a = number%2;
if(a == 0){
count1 = count1 + 1;
}
else{
count2 = count2 + 1;
}
}
else{
size = false;
break; //有错误就跳出循环
}
number = in.nextInt();
}
if(size){
System.out.println("奇数"+count1+"个,偶数"+count2+"个");
}
else{
System.out.println("error");
}
}
}
复制代码
作者:
水壶vs兔子
时间:
2015-7-2 09:40
学习了!
作者:
3084372073
时间:
2015-7-7 01:16
赞赞赞赞赞赞赞赞赞赞赞赞赞赞
作者:
杨基米德
时间:
2015-7-7 06:50
挺好的~谢谢分享!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2