scanner java重新输入_如何使用Scanner Java重复读取用户输入
我正在嘗試為我的程序創建一個簡單的菜單來讀取用戶輸入.這是代碼:
public void menu() {
String command;
System.out.println("To operate with words write: a");
System.out.println("To operate with products write: b");
System.out.print("
Give the command: ");
Scanner scanner = new Scanner(System.in);
command = scanner.nextLine();
if (command.equals("a")) {
System.out.println("
Good job! You have chosen the word program
");
System.out.println("You can only use the following commands: ");
System.out.println("exit - to exit the program");
System.out.println("add - to add a word into the map");
System.out.println("lookup - to lookup a word into the map
");
System.out.print("Give a command: ");
command = scanner.next();
while(scanner.hasNext()){
command = scanner.next();
if(command.equals("add")){
this.addWord();
}
System.out.print("Give a command: ");
command = scanner.next(); //Here I get the ERROR that throws Exception
}
}
scanner.close();
}
public static void main(String [] args)
{
HashTableInterface table = new HashTable();
Dictionary d = new Dictionary(table);
RepositoryInterface repo = new Repository(d);
ControllerInterface controller = new Controller(repo);
Console c = new Console(controller);
c.menu()
}
這是我得到的例外測試:
To operate with words write: a
To operate with products write: b
Give the command: a
Good job! You have chosen the word program
You can only use the following commands:
exit - to exit the program
add - to add a word into the map
lookup - to lookup a word into the map
Give a command: add
add
Give the word: mar
Give the word's plural: mere
The hash code for mar is: 3
Give a command: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at console.Console.menu(Console.java:56)
at test.Prog.main(Prog.java:26)
我從while循環中刪除了第二個命令= Scanner.next(),但是讓我僅讀取一次用戶輸入.怎么解決呢?
更新:AddWord方法:
public void addWord() {
Scanner scanner = new Scanner(new InputStreamReader(System.in));
System.out.print("Give the word: ");
String word = scanner.nextLine();
System.out.print("Give the word's plural: ");
String plural = scanner.nextLine();
scanner.close();
controller.addTheWord(word, plural);
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的scanner java重新输入_如何使用Scanner Java重复读取用户输入的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 赌场圣手(从不失手)——隐马尔可夫!
- 下一篇: html与java接口,JavaWeb学