我只是在学习 Java 的第二个学期,所以我的问题可能有一个非常简单的解决方案,但因此我已经纠结了几个小时。以下代码用于收集用户输入并将实例的信息存储在数组中。
没有机会为相册名称输入任何内容。输出结果如下。
Enter 5 songs
Title: title
Author: author1
Interpreter: int1
Year released: 2000
Album: File name: //Why doesn't this collect input and place File name: on the next line.
如果有人能指出正确的方向,我将不胜感激。我包括以下两种方法,以防它们与我的问题有关。感谢您提供的任何帮助。
public static void main(String[] args){
Scanner kybd = new Scanner(System.in);
Song[] songTest = new Song[5];
System.out.println("Enter 5 songs\n");
//TEST
for(Song x:songTest)
{
x = new Song();
System.out.print("Title: ");
x.setTitle(kybd.nextLine());
System.out.print("Author: ");
x.setAuthor(kybd.nextLine());
System.out.print("Interpreter: ");
x.setInterpreter(kybd.nextLine());
System.out.print("Year released: ");
x.setYearReleased(kybd.nextInt());
System.out.print("Album: ");
x.setAlbum(kybd.nextLine()); //this doesn't allow for input. it prints "File name:" and skips the user input for an album name. Also, when I comment out Year released, the problem goes away.
System.out.print("File name: ");
x.setFileName(kybd.nextLine());
System.out.print(x);
System.out.println();
}
public void setYearReleased(int y)
{
if (y>0 && y<2013)
this.yearReleased = y;
else
{
System.out.print ("This song is not that old");
this.yearReleased = -5;
}
}
public void setAlbum(String a)
{
this.album = a;
}
最佳答案
您需要在 kybd.nextInt()
之后执行 kybd.nextLine()
以便以下 kybd.nextLine()
执行不捕获为 nextInt()
按下回车键时使用的换行符。
关于Java作业(使用for循环填充数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12555334/