Scanner物件

我們可以通過scanner來獲取使用者的輸入

基本語法
  1. Scanner s = new Scanner(System.in);
nextLine():輸入
  1. import java.util.Scanner;
  2. public class hello {
  3. public static void main(String[] args) {
  4. //接收鍵盤資料
  5. Scanner scanner = new Scanner(System.in);
  6. System.out.println("使用nextLine的方式來輸出:");
  7. //判斷是否還有輸入
  8. if (scanner.hasNextLine()){
  9. String str = scanner.nextLine();
  10. System.out.println("輸出的內容是:" + str);
  11. }
  12. scanner.close();//凡是屬於IO流的類 如果不關閉會一直佔用資源
  13. }
  14. }
  • 以Enter為結束符,也就是說nextLine()方法返回的是輸入回車鍵之前所有的字元
  • 可以獲得空白
next():輸入
  1. import java.util.Scanner; //建立完Scanner後自動生成
  2. public class hello {
  3. public static void main(String[] args) {
  4. //建立一個掃描器物件,用於接收鍵盤資料
  5. Scanner scanner = new Scanner(System.in);//System.in是輸入
  6. System.out.println("使用next來接收:");
  7. //判斷使用者是否輸入字串
  8. if (scanner.hasNext()) {
  9. String str = scanner.next(); //使用next來接收
  10. System.out.println("輸出的內容為:" + str);
  11. scanner.close();//凡是屬於IO流的類 如果不關閉會一直佔用資源
  12. }
  13. }
  14. }
  • 一定要讀取到有效數字才可以1結束輸入
  • 對輸入有效字元之前遇到空白,next()方法會自動將其去掉
  • 只有輸入有效字元後才將其後面輸入的空白作為分隔符或者結束符
  • next()不能得到帶有空白的字串
關鍵語句
  1. String str = scanner.next();//使用next來接收。
  2. String str = scanner.nextLine();//使用nextLine來接收
判斷整數小數案例
  1. import java.util.Scanner;
  2. public class hello {
  3. public static void main(String[] args) {
  4. Scanner scanner = new Scanner(System.in);
  5. //從鍵盤接收資料
  6. int i = 0;
  7. float f = 0.01f;
  8. System.out.println("請輸入整數:");
  9. if (scanner.hasNextInt()){
  10. i = scanner.nextInt();
  11. System.out.println("整數資料:" + i);
  12. }else {
  13. System.out.println("你輸出的不是整數資料");
  14. }
  15. //——————————————————————————————————————————————————————
  16. System.out.println("請輸入小數:");
  17. if (scanner.hasNextFloat()){
  18. f = scanner.nextFloat();
  19. System.out.println("小數資料:" + f);
  20. }else {
  21. System.out.println("你輸出的不是小數資料");
  22. }
  23. scanner.close();
  24. }
  25. }
java求和,平均值
  1. import java.util.Scanner;//載入Scanner
  2. public class hello {
  3. public static void main(String[] args) {
  4. Scanner scanner = new Scanner(System.in);//獲取使用者輸入的資料
  5. double sum = 0; //求和 用高精度的double來賦值
  6. int n = 0; //計算輸入多少個數字
  7. System.out.println("請輸入數字");
  8. while (scanner.hasNextDouble()){ //迴圈語句
  9. double x = scanner.nextDouble(); //獲取使用者輸入的數字並儲存在變數x中
  10. n = n + 1; //給到n的初始值為0,因為我們要計算使用者輸入的數字,所以要+1
  11. sum = sum + x; //sum的初始值為0,使用者輸入的數字都儲存在x變數中,因此要+x
  12. }
  13. System.out.println("第"+ n + "個數的和為:" + sum);
  14. System.out.println("第" + n + "個數的平均值為:" + (sum / n ));
  15. scanner.close();//結束scanner
  16. }
  17. }