Java在演算法題中的輸入問題

foldn發表於2022-02-19

Java在演算法題中的輸入問題

在寫演算法題的時候,經常因為資料的輸入問題而導致卡殼,其中最常見的就是資料輸入無法結束。

1.給定範圍,確定輸入幾個資料

直接使用普通的Scanner輸入資料範圍,然後使用for迴圈輸入後續資料。

例如:

Scanner scanner = new Scanner(System.in);
//輸入資料的範圍
int n = scanner.nextInt();
for(int i = 0;i < n;i++){
    
    arrays[i] = scanner.nextInt();
}

2.沒有給定範圍,但是給出了結束符

使用while迴圈,當輸入結束符的時候退出迴圈

Scanner scanner = new Scanner(System.in);
//假設使用"0"作為結束符
//無限迴圈,在迴圈中和結束符進行比較,相同則停止迴圈
while(true){
    String str = scanner,nextLine();
    if(str == "0"){
        break;
    }
    //沒有結束,那麼對str進行處理
    
}
//判斷輸入的資料是否為"0",為"0"則停止迴圈,不為"0"則繼續迴圈
while(!scanner.hasNext("0")){
    String str = scanner.nextLine();
    //對str進行處理,只要輸入不為"0",就可以一直迴圈下去
}

3.沒有給定範圍,直接給定多組資料(這個最需要注意)

此時不能在使用Scanner進行輸入,因為無法結束,我們需要使用(BufferedReader)字元緩衝輸入流來進行輸入。

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while((str = br.readLine()) != null){
            //當讀入資料的下一行不為空時,進行迴圈,這裡對str進行處理
            
            
            
        }

4.Scanner中next()和nextLine()的區別

next()輸入不會包含空格以後的資料,只會輸入第一個空格前的字元,nextLine()輸入可以包括空格,只有遇見分隔符(例如回車)才會結束

Scanner scanner = new Scanner(System.in);
String str1 = scanner.next();//輸入hello world
String str2 = Scanner.nextLine();//輸入hello world
System.out.println(str1);//輸出hello
System.out.println(str2);//輸出hello world

相關文章