java基礎——Scanner的基礎和進階


Scanner對象

目的;用來獲取用戶的輸入

基本語法:

Scanner s = new scanner (System.in);

通過Scanner 類的next()和nextLine()方法,獲取輸入的字符串,

在讀取前我們一般需要使用hasNext()與hasNextLine()判斷是否還有輸入的數據。

  • next():

    1. 一定要讀取到有效字符后才可以可以結束輸入

    2. 對輸入有效字符之前遇到的空白,next()方法都會自動過濾掉

    3. 只有輸入有效字符之后,才將其后面輸入的空白作為分隔符,或者結束符號

    4. 結論:next()不能得到帶有空格的字符串

  • nextLine():

    1. 以Enter作為結束符,也就是說nextLine()方法返回的是輸入回車之前的所有字符

    2. 可以獲得中間的空白字符

    public static void main(String[] args) {

       // 創建一個掃描對象,用於接受鍵盤數據
       Scanner scanner = new Scanner(System.in);
       System.out.println("使用next方式接受:");

       // 判斷用戶有沒有輸入字符串
       if (scanner.hasNext()){

           //使用next方式接收
           String str = scanner.next();
           System.out.println("輸出的內容為:" + str);
      }

       //凡是屬於IO流的類,如果不關閉會一直占用資源,所以必須關閉掉
       scanner.close();
  }

   public static void main(String[] args) {
       //創建一個掃描對象,用於接受鍵盤數據
       Scanner scanner = new Scanner(System.in);
       System.out.println("使用nextline方式接受:");
       //判斷用戶有沒有輸入字符串
       if (scanner.hasNextLine()){

           //使用nextLine接受數據
           String str = scanner.nextLine();
           System.out.println("使用nextline方式接受的內容:"+str);

      }
       // 凡是屬於IO流的類, 在使用往后,必須要關閉
       scanner.close();
  }

   public static void main(String[] args) {
       // 建立一個掃描對象,用於接受鍵盤輸入數據
       Scanner scanner = new Scanner(System.in);

       System.out.println("等待用戶輸入:");
       //創建一個變量,用於儲存鍵盤輸入的數據
       String str = scanner.next();

       System.out.println("你輸入的數據是:"+str);
       //凡是IO流的類,都必須用完關閉
       scanner.close();
  }

Scanner進階

    public static void main(String[] args) {
       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{
           System.out.println("你輸入的不是整數");
      }

       System.out.println("請你輸入小數:");

       if (scanner.hasNextFloat()){
           f = scanner.nextFloat();
           System.out.println("你輸入的小數是"+f);
      }else{
           System.out.println("你輸入的數據不是小數");
      }
       scanner.close();
  }  


   public static void main(String[] args) {
       // 我們可以輸入多個數字,並求其總和與平均數,每輸入一個數字用回車確認,通過輸入非數字來結束輸入並輸出執行結果
       Scanner scanner = new Scanner(System.in);

       //和變量
       double sum = 0;
       //統計個數變量
       int m =0;

       //判斷循環是否還有輸入,並對每一次輸入進行記述和求和
       System.out.println("請輸入數據");
       while(scanner.hasNextDouble()){
           double x = scanner.nextDouble();
           m++;
           sum+=x;
           System.out.println("你輸入了第"+m+"個數據");
      }
       System.out.println("輸入的個數:"+ m);
       System.out.println("總和為:"+ sum);
       System.out.println("平均數:"+ (sum/m));
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM