无法使用Java中的Scanner从控制台读取输入

时间:2018-04-05 15:03:24

标签: java java.util.scanner

我正在尝试使用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后按下键盘上的空格键后,是否应该停止允许用户再提供输入?

此外,为什么我接下来打印两行而不是一行,为什么从控制台获取的值变为空?

1 个答案:

答案 0 :(得分:0)

除非您在调用方法时按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);
    }
}