题目
从键盘读入个数不确定的整数,并判断读入的正数和负数的个数,输入 为0时结束程序。
知识点
最简单“无限” 循环格式:while(true)
, for(;;)
,无限循环存在的原因是并不
知道循环多少次,需要根据循环体内部某些条件,来控制循环的结束。
while代码
package lesson.l3_while;import java.util.Scanner;public class WhileDemo1 {public static void main(String[] args) {Scanner scanner=new Scanner(System.in);int positive=0;int negative=0;while (true){int num=scanner.nextInt();if (num>0){positive++;}else if (num<0){negative++;}else {break;}}System.out.println("positive:"+positive+"\t"+"negative:"+negative);scanner.close();}
}
for代码
package lesson.l2_for;import java.util.Scanner;public class ForDemo7 {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int positive = 0;int negative = 0;for (;;){int num= scanner.nextInt();if (num>0){positive++;}else if (num<0){negative++;}else {break;}}System.out.println("positive:" + positive + "\t" + "negative:" + negative);scanner.close();}
}