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