日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

scanner java重新输入_如何使用Scanner Java重复读取用户输入

發布時間:2024/8/23 java 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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重复读取用户输入的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。