0

I know a lot of people have asked this but everyones answer is to use scanner.nextLine() however this does not work for me. I have this code:

if (option == 1) {
    System.out.println("What is the name of the goal the task is  under?: ");
    String goalName = scanner.next();
}

When I use .next() I can only get one word, however when I use .nextLine() the command line does not allow for the user to input anything so it asks "What is the name of the goal the task is under?:" and then continues on the program without letting input occur.

Madhawa Priyashantha
  • 9,208
  • 7
  • 28
  • 58
coder
  • 1
  • 1
  • 1
  • 3
  • @coder, since your program is small enough, could you please turn it into an [MCVE](http://stackoverflow.com/help/mcve)? That way we can run it for ourselves so we can help you out better. – Sam Estep Sep 22 '15 at 16:32
  • 1
    Did you use your scanner instance before entering the condition? – Yassin Hajaj Sep 22 '15 at 16:35

1 Answers1

4

The following test code works:

package asdfsadf;

import java.util.Scanner;


public class Asdfsadf {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("What is the name of the goal the task is  under?: ");
        String goalName = scanner.nextLine();
        System.out.println("You entered: ");
        System.out.print(goalName);
    }

}

So the only problem would be if you used scanner before this say you had scanner.nextInt() and that would leave an empty "end of the line" in the scanner. So the nextLine would take the end of the line from the previous call. To fix this, just create a new scanner object.

jthort
  • 409
  • 4
  • 14
  • What if I am not allowed to close the scanner and create a new scanner and I need to read the input? – k4b00m Dec 21 '20 at 17:10