如何在Java中暂停"for"以便我可以输入一些文本

RE6*_*60K -3 java for-loop

我需要解决一个问题,当输入整数时,这是用户想要在此输入旁边输入的行数(一些句子),如文本所述,如下所示:

第一行输入包含一个整数N,表示输入中的行数.接下来是N行输入文本.

我写了以下代码:

public static void main(String args[]) {

    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    String lines[] = new String[n];
        for(int i = 0; i < n; i++){
            System.out.println("Enter " + i + "th line");
            lines[i] = scan.nextLine();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

并与该计划的互动:

5(The user inputted 5)
Enter 0th line(Program outputted this)
Enter 1th line(Doesn't gave time to input and instantly printed this message)
Hello(Gave time to write some input)
Enter 2th line(Program outputted this)
How(User input)
Enter 3th line(Program outputted this)
Are(User input)
Enter 4th line(Program outputted this)
You(User input)
Run Code Online (Sandbox Code Playgroud)
  • 有什么问题?我无法输入第0行.
  • 建议一种更好的方法来输入n个行,其中n是用户提供给字符串数组的.

duf*_*ymo 7

呼叫将nextInt()离开新线路进行第0次呼叫以nextLine()进行消费.

另一种方法是始终使用nextLine()和解析输入字符串中的行数.

开始关注样式和代码格式.它提高了可读性和理解力.

public static void main(String args[]) {
    Scanner scan = new Scanner(System.in);
    int n = Integer.parseInt(scan.nextLine());
    String lines[] = new String[n];
    for (int i = 0; i < n; i++) {
        System.out.println("Enter " + i + "th line");
        lines[i] = scan.nextLine();
    }
}
Run Code Online (Sandbox Code Playgroud)