Multi-word scanner input in java?
15,623
Replace:
answer = myScanner.next();
With:
answer = myScanner.nextLine();
next will only read in the next value until it reaches a space or newline. You want to read in the full line before making the comparison
Author by
Cataroux
Updated on July 14, 2022Comments
-
Cataroux almost 2 years
So I'm trying to use if-else statement dependant upon the user's input. It works when the user's input is only one word, however, multiple word inputs go unrecognized and triggers the else statement. How can i resolve this?
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) { @SuppressWarnings("resource") Scanner myScanner = new Scanner(System.in); String answer; System.out.println("Catch the tiger or run away?"); answer = myScanner.next(); if (answer.equals("Catch the tiger" )) { System.out.println("You've been mauled by a tiger! What were you thinking?"); answer = myScanner.next(); } else { System.out.println("run away"); } } }
-
Suganthan Madhavan Pillai over 10 yearshow comes hasNextInt() here