TwoShorts
TwoShorts

Reputation: 548

Java - Using Scanner multiple times

I am currently trying to take in input from a user in the console, do some actions, and then take in more input from the console.

Scanner userInput = new Scanner(System.in);
while(true){
    System.out.print("Enter input: ");
    String foo = userInput.nextLine();
    //do stuff with foo
}

whenever I do this, the first run through of the loop works perfectly, but every subsequent run prints foo out as nothing, and it does not let me add more input.

//above code
System.out.println(foo);
//nothing prints

How should I make it so that it will prompt for input every time, and make sure that it doesn't just use a blank string?

Upvotes: 1

Views: 2979

Answers (2)

Scary Wombat
Scary Wombat

Reputation: 44854

Do you mean like

    Scanner userInput = new Scanner(System.in);
    while(true){
        System.out.print("Enter input: ");
        String foo = userInput.nextLine();

        if (foo.length () == 0) {
            break;
        }

        //do stuff with foo
        System.out.format("[%s]\n",foo);
    }

Upvotes: 3

Zac
Zac

Reputation: 11

there is no readLine method in Scanner class you may use it like that

Scanner userInput = new Scanner(System.in);
while (true) {
            System.out.print("Enter input: ");
            String foo = userInput.nextLine();
            System.out.println(foo);
}

Upvotes: -1

Related Questions