Java 处于循环中时next()和nextLine()之间的差异

Java 处于循环中时next()和nextLine()之间的差异,java,methods,Java,Methods,我正在使用数组,我想制作一个列表,用户可以为其长度设置一个值,然后用户还可以根据用户设置的长度添加一些字符串值。我想让程序显示用户输入给用户的列表(只是练习),我发现了next()和nextLine()的不同用法该nextLine()方法无法正常工作,因为我希望向数组中添加尽可能多的字符串。我的想法如下: System.out.println("Welcome to addingCourse wizard :)"); System.out.println("Please ente

我正在使用数组,我想制作一个列表,用户可以为其长度设置一个值,然后用户还可以根据用户设置的长度添加一些字符串值。我想让程序显示用户输入给用户的列表(只是练习),我发现了
next()
nextLine()的不同用法
nextLine
()方法无法正常工作,因为我希望向数组中添加尽可能多的字符串。我的想法如下:

System.out.println("Welcome to addingCourse wizard :)");
        System.out.println("Please enter the amount of your course: ");
        int z = input.nextInt();
        String[] course = new String[z];

        for (int i = 0; i < course.length ; i++) {

            course[i] = input.nextLine();
        }
        System.out.println("Ok. Here is your list...");

        for (int i = 0; i < course.length; i++) {

            System.out.println(course[i]);
        }
System.out.println(“欢迎使用添加课程向导:)”;
System.out.println(“请输入课程金额:”);
int z=input.nextInt();
字符串[]课程=新字符串[z];
for(int i=0;i

问题是
nextLine()
不允许我们在数组中添加所需的项目。例如,如果您希望列表为100,它将允许您只输入99个项目,尽管
next()
方法允许
课程。长度
项目并打印所有项目

请查看这些行

    int z = input.nextInt();
    String[] course = new String[z];

    for (int i = 0; i < course.length ; i++) {

        course[i] = input.nextLine();
    }

为什么会这样?回答第一个问题后,下一行的第一行将读取新行字符(按回车/回车)。您可以使用nextLine()而不是nextInt(),然后自己将字符串转换为int
int z = input.nextInt();
input.nextLine(); //Consumes the new line character