Scanner對象
Scanner scanner = new Scanner(System.in);
- 通過Scanner類的next()與nextLine()方法獲取輸入的字符串,在讀取前我們一般需要使用hasNext()與hasNextLine()判斷是否還有輸入的數據
- next()
- 一定要讀取到有效字符串后才可以結束
- 對輸入有效字符串之前遇到的空白,next()方法會自動將其去掉
- 只有輸入有效字符串后才將其后面輸入的空白作為分隔符或者結束符(Hello World只取Hello)
- next()不能得到帶有空格的字符串
- nextLine()
- 以Enter為結束符,nextLine()方法返回的是輸入回車之前的所有字符
- 可以獲得空白
//Scanner next()
//創建一個掃描器對象,用于接收鍵盤數據
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();
//---------------------------------------------------------
//Scanner nextLine()
//創建一個掃描器對象,用于接收鍵盤數據
Scanner scanner = new Scanner(System.in);
System.out.println("使用nextLine方式接收:");
//判斷用戶有沒有輸入字符串
if(scanner.hasNextLine()){
//使用nextLine方式接收
String str=scanner.nextLine();//程序會等待用戶輸入完畢
System.out.println("輸入的內容為:"+str);
}
//凡是屬于IO流的類如果不關閉會一直占用資源,要養成好習慣用完就關掉
scanner.close();
//---------------------------------------------------------
//scanner nextInt() nextFloat()
//從鍵盤接收數據
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("小數數據為:"+i);
}else{
System.out.println("輸入的不是小數數據");
}
//凡是屬于IO流的類如果不關閉會一直占用資源,要養成好習慣用完就關掉
scanner.close();
//---------------------------------------------------------
//Scanner 實例
//輸入多個數字,求總和以及平均數,每輸入一個數字用回車確認,通過輸入非數字結束輸入并輸出結果
Scanner scanner = new Scanner(System.in);
System.out.println("輸入數字:");
//和
double sum=0;
//計算輸入了多少個數字
int i=0;
//通過循環判斷是否還有輸入,并在里面對每一次求和進行統計
while(scanner.hasNextDouble()){
double v = scanner.nextDouble();
sum+=v;
i=i+1;
System.out.println("輸入第"+i+"個數,和為"+sum);
}
System.out.println(i+"個數總和為"+sum);
System.out.println(i+"平均數為"+(sum/i));
//凡是屬于IO流的類如果不關閉會一直占用資源,要養成好習慣用完就關掉
scanner.close();