1. 程式人生 > 實用技巧 >2020.12.08——JAVA流程控制—Scanner物件

2020.12.08——JAVA流程控制—Scanner物件

JAVA流程控制

Scanner物件

  • java.util.Scanner 是 Java5 的新特徵,我們可以通過 Scanner 類來獲取使用者的輸入。

  • 基本語法

Scanner s = new Scanner(systeam.in);
  • 通過Scanner類的next()與nextline()方法獲取輸入的字串,在讀取前使用hasNext()和hasNextLine判斷是否還有輸入的資料

    //建立一個掃描器物件,用於接收鍵盤資料
Scanner s = new Scanner(System.in);
System.out.println("使用next方式接收:");

//判斷使用者是否輸入字串,輸入111 222,回車
if (s.hasNext()) {
String str = s.next();
System.out.println("next輸入的內容為:" + str);//輸出111
}
if (s.hasNextLine()) {
String strlin = s.nextLine();
System.out.println("nextLine輸入的內容為:" + strlin);//輸出111 222
}
s.close();
  • next()

    • 一定要讀取到有效的字串後才可結束輸入

    • 對輸入有效字串之前的空格,next()方法會自動將其去掉

    • 只有輸入有效字元後才將其後面的空格作為分隔符或者結束符

    • next()不能得到帶有空格的字串

  • nextline()

    • 以enter為結束符,也就是得到回車之前的所有字元

    • 可以獲得空格

  • 簡單的流程判斷

    Scanner scanner = new Scanner(System.in);
int i = 0;
float f = 0.0f;
System.out.println("請輸入數字:");
if (scanner.hasNextInt()) {
i = scanner.nextInt();
System.out.println("得到整數" + i);
} else if (scanner.hasNextFloat()) {
f = scanner.nextFloat();
System.out.println("得到小數" + f);
} else {
System.out.println("輸入的不是數字");
}

scanner.close();
  • 利用while進行迴圈判斷,求和

    Scanner scanner = new Scanner(System.in);
int n = 0;
double sum = 0;

System.out.println("請輸入數字,結束請輸入非數字");//依次輸入1,2,3,a
while (scanner.hasNextDouble()) {
double d = scanner.nextDouble();
n++;
sum = sum + d;
}
System.out.println("個數為:" + n + ",總和為:" + sum);//個數為:3,總和為:6.0
scanner.close();