random-xyz
random-xyz

Reputation: 137

java scanner does not accept two words with space in between

I'm trying to create a simple project that will ask the user true or false and if true then the scanner is gonna keep storing the category name in an arraylist. And it works fine until you enter two words with a space in the category name "first second" for example for some reason it jump into the condition true or false and check that i have entered another word than true or false and execute the catch clause . I've tried using both scanner.next or nextline , nextline just jump into true or false without asking for category name. Please help. Thank you so much.

public class MainClass {


public static boolean check = false;
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    Categories c = new Categories();

    System.out.println("Please enter true if you want to add a category \n or false if not");

    try {
        check = in.nextBoolean();
    } catch (InputMismatchException e) {
        System.out.println("Sorry you must put true or false!!!");
        System.exit(0);

            }


    while (check) {
        System.out.println("Please enter category name");
        c.category.add(in.next().toString());
        System.out.println("do you want to add more true or false");

        try {
            check = in.nextBoolean();
        } catch (InputMismatchException e) {
            System.out.println("Sorry you must put true or false!!!");
            System.exit(0);
        }

    }

    System.out.println("Thank you all categories are added");
    System.out.println(c.category);





}

}

Upvotes: 1

Views: 756

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Change

check = in.nextBoolean();

to

check = in.nextBoolean();
in.nextLine(); // to swallow end of line token

and change

c.category.add(in.next().toString());

to:

c.category.add(in.nextLine()); // to get the whole line

Upvotes: 2

Lysenko Andrii
Lysenko Andrii

Reputation: 496

You can use InputStreamReader wrapped around BufferedReader:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
reader.readLine(); // this will read two words

Upvotes: 0

Related Questions