黑马程序员技术交流社区

标题: while的应用 [打印本页]

作者: fantianfei    时间: 2015-7-2 09:31
标题: while的应用
你的程序要读入一系列正整数数据,输入-1表示输入结束,-1本身不是输入的数据。程序输出读到的数据中的奇数和偶数的个数。输入一系列正整数,整数的范围是(0,100000)

我的思路:
1.需要两个变量来分别记录奇数和偶数的个数;2.需要用到循环来读入数据;3.根据条件限制来判断循环条件

  1. public class Test{
  2.     public static void main(String[] args) {
  3.         //获取控制台输入
  4.         Scanner in = new Scanner(System.in);
  5.         int count1 = 0;
  6.         int count2 = 0;
  7.         int number = in.nextInt();
  8.         boolean size = true;//用来判断输入的数是否在取值范围内
  9.         while(number != -1){
  10.             if(number>0 && number<10000){
  11.                 int a = number%2;
  12.                 if(a == 0){
  13.                     count1 = count1 + 1;
  14.                 }
  15.                 else{
  16.                     count2 = count2 + 1;
  17.                 }
  18.             }
  19.             else{
  20.                 size = false;
  21.                 break; //有错误就跳出循环
  22.             }
  23.             number = in.nextInt();
  24.         }
  25.         if(size){
  26.             System.out.println("奇数"+count1+"个,偶数"+count2+"个");
  27.         }
  28.         else{
  29.             System.out.println("error");
  30.         }
  31.     }
  32. }
复制代码

作者: 水壶vs兔子    时间: 2015-7-2 09:40
学习了!
作者: 3084372073    时间: 2015-7-7 01:16
赞赞赞赞赞赞赞赞赞赞赞赞赞赞
作者: 杨基米德    时间: 2015-7-7 06:50
挺好的~谢谢分享!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2