Kevin Goodenough
Kevin Goodenough

Reputation: 195

Java Homework (using a for loop to fill an array)

I am only in my second semester of java so there is probably a very simple solution to my problem, but I have been pulling my hair our for hours because of this. The following code is being used to collect user input and store instance's info in an array.

There isn't an opportunity to input anything for the album name. The output is as follows.

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.

If anyone could point me in the right direction I would greatly appreciate it. I included the two methods below in case they have something to do with my problems. Thanks for any help you can provide.

    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;
}

Upvotes: 1

Views: 580

Answers (2)

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26058

x.setYearReleased(kybd.nextInt());

does not do anything with the end of the line character and will remain on the line giving the behavior you see. A quick fix could be to just add another ktbd.nextLine(); after this to skip anything else on the line after the next int.

System.out.print("Year released: ");
x.setYearReleased(kybd.nextInt());
kybd.nextLine()
System.out.print("Album: ");
x.setAlbum(kybd.nextLine());

Upvotes: 2

You need to do a kybd.nextLine() after kybd.nextInt() so that the following kybd.nextLine() does not capture the newline used when pressing enter for the nextInt().

Upvotes: 3

Related Questions