0

I can't find the error in my code. It works when I move the commands around and ask for two string inputs in a row, but when I ask for a string then an integer then a string again, I get no response from the keyboard for the second string.

I have cut and paste the String option = scan.nextLine(); to different locations. it works before the integer input but not after. I see the prompt in the command window to type a user input but when I hit the keys on the keyboard nothing happens

import java.util.Scanner;

public class Assignment6 {

    public static void main(String[] args) {

        // Create scanner
        Scanner scan = new Scanner(System.in);

        // variables
        int year;
        int numQuestions;
        String name;


        // Create Geek
        System.out.println("Please enter the geeks name: ");
        name = scan.nextLine();

        System.out.println("Please enter the number of questions the geek answers: ");
        numQuestions = scan.nextInt();

        System.out.println("\nPlease enter a command or type: ");
        String option = scan.nextLine();

    }

}

Using eclipse and java

dkb
  • 3,238
  • 3
  • 26
  • 41
  • 2
    Please see https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo ... does that help? – GhostCat Jun 23 '19 at 17:35
  • That did help. I was not able to get either of those solution to work so I just created a string variable and added it to the code now it skips the fix input and asks the required ones – KrisEverhart Jun 23 '19 at 18:09

1 Answers1

0

nextInt() method in Scanner class takes the string of the number itself, and only the number itself. In your case, the char '\n' (newline) is still in your input, and that's why nextline() won't work properly the second time you use it.

To fix this, you can read 1 char from the standard input using System.in.read() after your scan.nextInt() call. In this way, you are cleaning the newline char from your input, and let scan.nextLine() read the next line properly.