基礎循環輸入求值


Scanner:


字符串:


 

package com.cheng.scanner;

import java.util.Scanner;

public class Demo01 {
   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);//創建一個掃描器對象,用於接收數據
       System.out.println("請輸入數據:");
       String str = scanner.nextLine();//接收輸入到字符串str
       System.out.println("輸出的內容為:"+str);
       scanner.close();//關閉scanner 不在占用資源

       /*
       判斷有無輸入:
       if(scanner.hasNext()){
       String str = scanner.next();
       System.out.println("輸出的內容為:"+str);
       }
       上面的輸入為next還可為nextline形式
       只需把上面的next依次替換即可
       next和nextline區別
       next:接收到有效字符后遇見的第一個空格之后的就都不算了
       nextline:直到接收到回車才結束
        */
  }
}

輸入整數和浮點數:

package com.cheng.scanner;

import java.util.Scanner;

public class Demo02 {
   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);

       int i = 1;
       float f = 1.1f;

       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();
  }
}
package com.cheng.scanner;

import java.util.Scanner;

public class Demo03 {
   //輸入多個數字 求其總數和平均值 當輸入的不是數字時結束輸入
   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
      double sum = 0;
      int count = 0;
       System.out.println("請輸入數字:");
      while (scanner.hasNextDouble()){
          double d = scanner.nextDouble();
          count++;
          sum+=d;
      }
       System.out.println("平均值為:" + sum/count);
       System.out.println("總數為:" + sum);

      scanner.close();
  }
}

 

 

 


免責聲明!

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



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