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