☞題目要求:
輸入一批整數,輸出其中的最大值和最小值,輸入數字0時,結束循環
1 import java.util.Scanner; 2 3 /** 4 * 功能描述: 輸入一批整數,輸出其中的最大值和最小值,輸入數字0時,結束循環 5 * 6 * @Author: apple. 7 * @Date: 2019/11/22 10:18 AM 8 */ 9 public class Demo04 { 10 static Scanner sc = new Scanner(System.in); 11 12 public static void main(String[] args) { 13 int max;// 最大值 14 int min;// 最小值 15 int num;// 輸入的整數 16 System.out.print("請輸入一個整數(輸入0結束)"); 17 while (!sc.hasNextInt()) {//判斷輸入的是否為整數,不是整數則進入循環 18 System.out.print("輸入的有誤重新輸入:"); 19 sc.next(); 20 } 21 max = min = num = sc.nextInt();// 以第一個輸入的數作為初始值 22 while (num != 0) {// 把零排除在外,0用作中止程序 23 if (num > max) { 24 max = num;// 如果大於目前的最大值,進行替換 25 } 26 if (num < min) { 27 min = num;// 如果小於目前的最小值,進行替換 28 } 29 System.out.print("請輸入一個整數(輸入0結束):"); 30 while (!sc.hasNextInt()) { 31 System.out.print("輸入的有誤重新輸入:"); 32 sc.next(); 33 } 34 num = sc.nextInt(); 35 } 36 System.out.println("最大值為:" + max + " 最小值為:" + min); 37 } 38 39 40 }