3

I'm writing a program that includes a method to search for a song in an array of songs. Below is the code for this particular section that's giving me trouble. The kybd has already been initiated, and below is the code for the section, using the searchSong() method in my class.

    System.out.println("To search for a song, enter the following:");
    System.out.print("Title: ");
    searchT = kybd.nextLine();
    System.out.print("Author: ");
    searchAu = kybd.nextLine();
    System.out.print("Interpreter: ");
    searchI = kybd.nextLine();
    System.out.print("Album: ");
    searchAl = kybd.nextLine();
    System.out.println("Found this:"+'\n'+lib.searchSong(searchT, searchAl, searchAu, searchI));

When I run the program, it prints "Title" but doesn't let me enter the search term, it just skips straight to "Author." Below is the output I get.

To search for a song, enter the following:
Title: Author: search
Interpreter: search
Album: search

Can someone explain to me why this might be happening, and maybe how to fix it? I've checked and double checked my code and I can't figure it out.

Solved! I was using nextInt() for another method previously in the program. I took the advice in the question @Rohit Jain suggested and used a blank nextLine() before this section of code, and now it works. Thanks!

Joe F
  • 3,706
  • 1
  • 12
  • 13
alu
  • 190
  • 1
  • 9

1 Answers1

2

System.out.print("Title: "); should be replaced by System.out.println("Title: ");

I am assuming that

Scanner kybd = new Scanner(System.in);

since i see kybd.nextLine() method

Actually, the input is not getting skipped, just that Title: and Author: getting printed next to each other because of print instead of println. Did you try typing text and hitting enter? I am sure you will be allowed to type and enter text twice

sanbhat
  • 16,864
  • 6
  • 46
  • 62