簡體   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