輸入多個整數,判斷讀入的正數和負數的個數

 1 /*  2  題目:  3  從鍵盤讀入個數不肯定的整數,並判斷讀入的正數和負數的個數,輸入  4  爲0時結束程序。  5 */  6  7 import java.util.Scanner;  8  9 public class ForWhileTest { 10 public static void main(String[] args) { 11 // 建立鍵盤輸入對象 12 Scanner sc = new Scanner(System.in); 13 14 int positiveNum = 0; // 正數個數 15 int negativeNum = 0; // 負數個數 16 17 while (true) { 18 19 // 接收鍵盤輸入的整數 20 int num = sc.nextInt(); 21 22 if (num > 0) { 23 positiveNum++; 24 } else if (num < 0) { 25 negativeNum++; 26 } else { 27 break; // 輸入爲0時,跳出循環 28  } 29 30  } 31 32 System.out.println("正數個數:" + positiveNum); 33 System.out.println("負數個數:" + negativeNum); 34  } 35 }

 

相關文章
相關標籤/搜索