Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 读取整数或字符输入的简单方法是什么?_Java - Fatal编程技术网

Java 读取整数或字符输入的简单方法是什么?

Java 读取整数或字符输入的简单方法是什么?,java,Java,由于无法调用nextChar(),因此我不确定如何读取可以是2个整数(用空格分隔)或一个字符的输入。帮助?您必须使用下一步。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

由于无法调用nextChar(),因此我不确定如何读取可以是2个整数(用空格分隔)或一个字符的输入。帮助?

您必须使用
下一步。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...
}

字符串比较应该是

"q".equals(next)
=
比较指向同一对象与否的两个引用。通常用于原语比较


.equals()
比较对象必须确定的相等值

首先,不要使用
if(next==“q”)
来比较字符串。请注意,即使
“q”
是单个字符,它仍然是
字符串
对象。您可以使用
next.charAt(0)
来获取
char
'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);
}