在最后一行读取键盘输入时扫描仪的奇怪组合

时间:2021-01-23 21:51:32

While reading the input of the keyboard with Scanner(System.in), the program stops at the last line of my input, and it continues working only after I press enter in the input console.

在使用Scanner(System.in)读取键盘输入时,程序在输入的最后一行停止,只有在输入控制台中输入后才能继续工作。

For example, if I want to read this

例如,如果我想读这个

3
f
g
h

instead, I get

相反,我明白了

3
f
g

h

My program is quite simple,

我的程序很简单,

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);
    int count = sc.nextInt();
    sc.nextLine();
    System.out.println("\n"+count);
    while(count>0) {
        System.out.println(sc.nextLine());
        count--;

    }
}

I can't understand what is happening. I'll apreciate your help.

我无法理解发生了什么。我会帮助你。

1 个解决方案

#1


0  

I haven't used the Scanner in a while but I hope this can be useful:

我有一段时间没有使用扫描仪,但我希望这可能有用:

String string;
java.util.Scanner mainScanner = new java.util.Scanner(System.in);
while( mainScanner.hasNextLine() )
{
    string = mainScanner.nextLine();
    // use string
}

#1


0  

I haven't used the Scanner in a while but I hope this can be useful:

我有一段时间没有使用扫描仪,但我希望这可能有用:

String string;
java.util.Scanner mainScanner = new java.util.Scanner(System.in);
while( mainScanner.hasNextLine() )
{
    string = mainScanner.nextLine();
    // use string
}