![](/img/trans.png)
[英]Reading a character input in the console using the Scanner Class in Java
[英]Trouble reading input from console using Scanner in Java
我正在嘗試使用Java中的Scanner
類從控制台讀取一堆輸入。 以下是我的代碼:
System.out.println("Please enter the number of vertices");
Scanner scanner = new Scanner(System.in);
int numOfVertices = scanner.nextInt();
System.out.println("Please name the vertices");
HashMap<String, Integer> nameNumMap = new HashMap<String, Integer>();
for (int i = 0; i < numOfVertices; i++) {
nameNumMap.put(scanner.next(), i);
}
Set<String> keySet = nameNumMap.keySet();
String[] response = new String[numOfVertices];
int i = 0;
for (String key : keySet) {
System.out.println("Please enter the vertices connected to " + key + " separated by ','");
String response[i] = scanner.nextLine();
if (i<numOfVertices)
i++;
}
System.out.println("Responses are:");
for (String res : response) {
System.out.println(res);
}
在控制台輸出
Please enter the number of vertices
3
Please name the vertices
A B C D E F
Please enter the vertices connected to A separated by ','
Please enter the vertices connected to B separated by ','
A
Please enter the vertices connected to C separated by ','
D
null
null
null
如果numOfVertices
為3,那么掃描程序類是否應該在第3個元素之后理想地停止輸入? 輸入C后在按下鍵盤上的空格鍵后,是否不應該停止允許用戶提供更多輸入?
此外,為什么我接下來要打印兩行而不是第一行,為什么從控制台獲取的值為null?
除非在調用方法時按Enter或輸入模式,否則Scanner.next()將不會讀取輸入。 您也可以傳入掃描儀的定界符,以便僅讀取定界符中的字符串,但是對於您所擁有的內容,我相信模式匹配會更簡單。
下面是修改后的代碼,以便它接受文本值並在由空格分隔的一行中讀取它們。
如果將模式匹配應用於next()
,將很容易更改讀取頂點的部分以讀取逗號之間的字符串。
static void main(String[]args){
System.out.println("Please enter the number of vertices");
Scanner scanner = new Scanner(System.in);
int numOfVertices = Integer.parseInt(scanner.nextLine());
System.out.println("Please name the vertices");
HashMap<String, Integer> nameNumMap = new HashMap<String, Integer>();
for (int i = 0; i < numOfVertices; i++) {
nameNumMap.put(scanner.next("\\w"), i);
}
scanner.skip("\\s*\\w*");
Set<String> keySet = nameNumMap.keySet();
String[] response = new String[numOfVertices];
int i = 0;
for (String key : keySet) {
System.out.println("Please enter the vertices connected to " + key + " and press enter");
response[i] = scanner.next();
if (i<numOfVertices)
i++;
}
System.out.println("Responses are:");
for (String res : response) {
System.out.println(res);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.