《怪物獵人崛起》2.0版本狩獵笛配裝分享
阿新 • • 發佈:2021-05-20
Scanner物件
可以通過Scanner類來獲取使用者的輸入
基本語法
Sanner s=new Scanner(System,in);
通過Scanner類的next()與nextLine()方法獲取輸入的字串,在讀取前一般需要使用hasNext()與hasNextLine()判斷是否還有輸出的資料
next()
public class v { //next() public static void main(String[] args) { //建立一個掃描器物件,用於接收鍵盤資料 Scanner scanner = new Scanner(System. in);//執行後,程式會等待使用者輸入完畢,不然會一直卡住,在下方執行的那個裡面輸入個東西,點回車,才會結束 //先輸入new Scanner(System.in);,再點黃燈就OK System.out.println("使用next方式接收"); //判斷使用者有沒有輸入字串 if (scanner.hasNext());{ //使用next方式接收 String str=scanner.next(); System.out.println("輸出的內容為:"+str); } //凡是屬於IO流的類如果不關閉會一直佔用資源,要養成好習慣,用完就關掉 scanner.close(); } }
nextLine()
//nextLine() import java.util.Scanner; public class vv { public static void main(String[] args) { //從鍵盤接收資料 Scanner scanner = new Scanner(System.in); System.out.println("使用nextLine方式接收"); //判斷是否還有輸入 if (scanner.hasNextLine());{ String str=scanner.nextLine(); System.out.println("輸出的內容為:"+str); } scanner.close(); }
next()與nextLine()的區別
next(): 不能得到帶有空格的字串。
將可空格作為結束符或分隔符 只能提取到空格前,空格後的自動忽略 eg:hello world 只能輸出hello
nextLine():以Enter為結束符 輸出的是回車之前所有字元
可以獲得空白
還可以不用if語句
import java.util.Scanner; public class vvv { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("請輸入資料:"); String str=scanner.nextLine(); System.out.println("輸出的內容為:"+str); scanner.close(); } }
關於小數
import java.util.Scanner;
public class vvvv {
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("==================================");
System.out.println("請輸入小數");
//如果 那麼
if (scanner.hasNextFloat()){
f= scanner.nextFloat();
System.out.println("小數資料"+f);
}
//否則
else{
System.out.println("輸入的不是小數資料");
}
scanner.close();
}
}
和與平均值
//和與平均值
import java.util.Scanner;
public class v4 {
public static void main(String[] args) {
//可以輸入多個數字,並求其總和和平均數,每輸入一個數字用回車確認,通過輸入非數字來結束輸入並輸出結果
Scanner scanner=new Scanner(System.in);
//和
double sum=0;
//計算輸入了多少個數字
int m=0;
//通過迴圈判斷是否還有輸入,並在裡面對每一次進行求和和統計
while (scanner.hasNextDouble()){
double x=scanner.nextDouble();
m=m+1;//或寫成m++
sum=sum+x;
System.out.println(m+"個數的和為"+sum);
System.out.println(m+"個數的平均值是"+(sum/m));
}
scanner.close();
}
}
注意
每個都要加結束語句 scanner.close();
不然不會結束
寫的時候先寫上在寫中間的