0

When I run this code it skips the first line("Input first name:") and ask for the lastname. How do i fix this?

public static void newProduct() {
    System.out.println("Input first name: ");
    String fname = scan.nextLine();
    System.out.println("Input last name: ");
    String lname = scan.nextLine();
}

The output everytime I run this is:

Input first name: <User cannot input as this line gets skipped>
Input last name: <User can input>

Thanks in advance.

Supremo
  • 13
  • 6
  • 2
    Do you have any other `nextXXX` somewhere else before this line? Perhaps in another method? – Maroun Dec 11 '17 at 11:27
  • @MarounMaroun YES!, Thank you. you can add it in the comment ill check it as the answer once the cooldown is done. – Supremo Dec 11 '17 at 11:29
  • This is happening because `nextInt`, for example, doesn't consume the new line character (the enter key you press), but only digits. This "leftover" character is then consumed in your next `nextLine`. The solution would be using another scanner, or adding another `nextLine` before. – Maroun Dec 11 '17 at 11:30

1 Answers1

-1

Try this

public class Readname {


public static void main(String[] args) {


            Scanner scan = new Scanner(System.in);

            System.out.print("Give a First Name :");
            String text = scan.nextLine();
            System.out.print("Give a Last Name :");
            String text2 = scan.nextLine();
            System.out.println("Full Name: "+text+" "+text2);//to bond the last and first name 

}

}
sasuri
  • 942
  • 1
  • 11
  • 26
  • I fixed the problem I had another method that uses scan.nextInt(); i just needed to add scan.nextLine(); Thanks for the help anyway – Supremo Dec 11 '17 at 11:30