java Scanner輸入多行數據后按enter自動結束輸入


重點:使用兩個Scanner

如:將輸入的所有數存入數組並輸出

輸入: 12  2  43

          1 9 

           87  23  10 28 45 68

輸出:

[12, 2, 43, 1, 9, 87, 23 ,10,28,45,68]

public static void saveInput(){
    Scanner sc = new Scanner(System.in);
    //讀取直到沒有新的輸入
    ArrayList<Integer> save = new ArrayList<>();
    while(true){
//       輸入兩次enter結束
        String s = sc.nextLine();
        if ("".equals(s)) break;
        Scanner s2 = new Scanner(s);
        while(s2.hasNextInt()) save.add(s2.nextInt());
    }
    System.out.println(save.toString());
}

 

 

常見的直接用sc.hasNext()來判斷並不能自動結束輸入:

public static void saveInputWrong(){
    ArrayList<Integer> save = new ArrayList<>();
    Scanner sc = new Scanner(System.in);
    while(sc.hasNext()){
        save.add(sc.nextInt());
    }
    System.out.println(save);
}

 


免責聲明!

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



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