繁体   English   中英

使用 ArrayList 创建选项菜单以添加字符串对象。 当输入包含空格“hello there”时,我得到 java.util.InputMistmachException

[英]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;
            }

        }`

我想知道为什么我会收到此错误,如果我尝试输入由多个单词组成的字符串。 例如,如果我输入“Hello Peter”。

提前感谢您的帮助。

正如 maloomeister 所述, Scanner.next()只会读取一个单词(除非您有不同的分隔符)。 要阅读整行(所有单词),请使用Scanner.nextLine()

runescape.add(input.nextLine());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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