我如何使用多个扫描仪

时间:2015-02-10 01:42:13

标签: java java.util.scanner

我无法弄清楚如何允许输入由用户想要的线路组成。输入将至少包含1行。在第一行将是一个整数,这个整数假设告诉程序后面将跟随多少行,例如。

    5
    line1
    line2 
    line3
    line4
    line5

我该怎么办?是否有一种扫描仪允许这种情况或者我应该使用循环?

1 个答案:

答案 0 :(得分:1)

您不需要多个Scanner实例来处理此问题。只需使用一个循环就足够了。

Scanner sc = new Scanner(System.in);
int nbLines = sc.nextInt();
sc.nextLine(); //consume the line separator token 
for(int i = 0; i < nbLines; i++) {
    String line = sc.nextLine();
    //do something with the line
}
相关问题