一个简单的方法读取既可以是整数也可以是字符的输入是什么?

3

由于无法调用nextChar()方法,我不确定该如何读取输入内容。输入可能是两个整数(以空格分隔)或一个字符。请帮忙解决?

3个回答

3
首先,不要使用if (next=="q")来比较字符串,而应该使用if (next.equals("q"))。请注意,即使"q"只是一个字符,它仍然是一个String对象。您可以使用next.charAt(0)来获取'q'这个字符,然后您确实可以使用next == 'q'
另外,不要使用next(),而应该使用nextLine(),如果用户没有输入"q",则需要拆分行以获取两个整数。否则,如果您调用了两次next(),并且您只输入了"q",那么程序将永远不会退出,因为扫描器将等待用户输入以从第二个next()返回:
String next = keyboard.nextLine();
if (next.equals("q")) {
  System.out.println("You are a quitter. Goodbye.");
}
else {
  String[] pair = next.split(" ");
  int r = Integer.valueOf(pair[0]);
  int c = Integer.valueOf(pair[1]);
  System.out.printf("%d %d\n", r, c);
}

2

字符串比较应该是

"q".equals(next)

== 用于比较两个引用是否指向同一个对象。通常用于原始类型的比较。

.equals() 用于比较对象的值以确定它们是否相等。


2

您需要使用next.equals("q")。一般情况下,==只应用于原始数据类型。请尝试以下代码:

Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a coordinate [row col] or press [q] to quit: ");
String next = keyboard.nextLine();

if (next.equals("q")){  // You can also use equalsIgnoreCase("q") to allow for both "q" and "Q".
    System.out.println("You are a quitter. Goodbye.");
    isRunning=false;
}
else {
    String[] input = next.split(" ");
    // if (input.length != 2) do_something (optional of course)
    int r = Integer.parseInt(pair[0]);
    int c = Integer.parseInt(pair[1]);
    // possibly catch NumberFormatException...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接