我只是在Java的第二个学期,所以可能有一个非常简单的解决方案,但是由于这个原因,我已经花了好几个小时了。以下代码用于收集用户输入并将实例的信息存储在数组中。

没有机会为专辑名称输入任何内容。输出如下。


  输入5首歌曲
  
  标题:title
  作者:author1
  口译员: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()的Enter时使用的换行符。

10-08 01:34