更多精彩文章歡迎關注公衆號「Java之康莊大道」java
利用for循環和while循環分別作到,從鍵盤讀取任意數,輸入0自動跳出無限循環,並判斷有幾個正數幾個負數。spa
1.for循環的無限循環:code
1 import java.util.Scanner;//引用Scanner類用於讀取鍵盤輸入 2 class TestXunHuan 3 { 4 public static void main(String[] args) 5 { 6 int a=0;//記錄正數的個數 7 int b=0;//記錄負數的個數 8 Scanner s=new Scanner(System.in); 9 for(;;){ 10 System.out.println("請輸入一個整數"); 11 int sum=s.nextInt(); 12 if(sum>0) 13 a++; 14 else if (sum<0) 15 b++; 16 else 17 break; 18 } 19 System.out.println("其中一共有"+a+"個正數;有"+b+"個負數"); 20 } 21 }
運行結果:blog
2.while循環的無限循環for循環
1 import java.util.Scanner;//引用Scanner類用於讀取鍵盤輸入 2 class TestXunHuan 3 { 4 public static void main(String[] args) 5 { 6 int a=0;//記錄正數的個數 7 int b=0;//記錄負數的個數 8 Scanner s=new Scanner(System.in); 9 while(true){ 10 System.out.println("請輸入一個整數"); 11 int sum=s.nextInt(); 12 if(sum>0) 13 a++; 14 else if (sum<0) 15 b++; 16 else 17 break; 18 } 19 20 System.out.println("其中一共有"+a+"個正數;有"+b+"個負數"); 21 } 22 }
運行結果:class