简体   繁体   中英

Creating an option menu using an ArrayList to add objects of string. When input contains space "hello there" I get java.util.InputMistmachException

`System.out.println();
        ArrayList<String> runescape = new ArrayList<String>();

        while (true) {
            display();

            int optionNum = input.nextInt();
            
            if (optionNum == 1) {
                System.out.print("Enter a String : ");
                runescape.add(input.next());
                System.out.println("Element Added");
            } 
            else if (optionNum == 2) {
                
                System.out.print("Enter String to remove :");
                String remov = input.next();
                if (runescape.contains(remov)) {
                    runescape.remove(new String(remov));
                    System.out.print("The String been removed.");
                }else
                    System.out.println("That String does not exist");
            } else if (optionNum == 3) {
                System.out.print("Your list: " + runescape);
            } else if (optionNum == 4) {
                System.out.print("You have exited the program.");
                break;
            }

        }`

I am wondering why I get this error, if I try entering a String made up of multiple words. For example if I enter "Hello Peter".

Thank you for the help in advance.

As stated by maloomeister, Scanner.next() will only read a single word (unless you have a different delimiter). To read a full line (all words), use Scanner.nextLine() :

runescape.add(input.nextLine());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM