Java家庭作业(使用for循环填充数组)
问题描述:
我只在我的第二学期的java中,所以可能有一个非常简单的解决方案来解决我的问题,但因为这个原因,我一直在拉我的头发。以下代码正在用于收集用户输入并将实例的信息存储在数组中。Java家庭作业(使用for循环填充数组)
没有机会为专辑名称输入任何内容。输出如下。
进入5首歌曲
标题:标题
作者:作者1
解释:INT1
发行年份:2000
专辑:文件名://为什么不这样收集的输入和地点文件名:在下一行。
如果任何人都可以点我在正确的方向,我将不胜感激。我在下面列出了两种方法,以防他们与我的问题有关。感谢您的任何帮助,您可以提供。
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.nextLine()
kybd.nextInt()
后,使下面的kybd.nextLine()
不捕获迫切要求nextInt()
输入时的换行使用。
+0
非常感谢您的帮助。我偶尔碰到一些非常令人沮丧的菜鸟错误。此外,我删除了一首歌曲需要的限制
答
x.setYearReleased(kybd.nextInt());
不与行字符的结尾做任何事情,将继续上线让你看到的行为。快速修复可能是在此之后添加另一个ktbd.nextLine();
以在下一个int之后跳过该行上的其他任何内容。
System.out.print("Year released: ");
x.setYearReleased(kybd.nextInt());
kybd.nextLine()
System.out.print("Album: ");
x.setAlbum(kybd.nextLine());
我喜欢如何设置发布年份到2014年的结果'这首歌曲不是那么古老'打印在标准输出上。 – sehe