我正在开发一个程序,它会要求用户输入一个整数,然后输入另一个整数,并将它们作为图形点。然后它会告诉他们之间的距离。用户必须输入一个整数或按“Q”退出。如果是其他内容(不是整数或字母“Q”),它会告诉他们这是不正确的,请重试。我认为这就是我可以实现的方法,但它返回错误 cannot find symbol
。非常感谢您的帮助!
import java.util.Scanner;
public class PointCheck{
public static void main(String[] args){
try {
System.out.println("Welcome");
System.out.println("To quit at anytime please type \"Q\". Enter point:");
char Q = 'Q';
char q = 'q';
Scanner scan = new Scanner (System.in);
input = scan.next();
while (input.hasNext()) {
if (input.hasNextInt()) {
System.out.println("Int input");
}
else if (input.equals("Q")) {
System.out.println("Exiting");
}
/*else {
System.out.println("You did not enter a valid value. Please enter a number or \"Q\" to quit.");
}*/
}
}
catch(Exception e){
System.out.println("Exiting Program.");
}
}
}
如果我不注释掉最后一个 else 语句,它就会默认为该语句并永远循环我的错误消息。
最佳答案
我对你的代码做了一些修改,希望有帮助:)
public class PointCheck {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
System.out.println("Welcome");
System.out.println("To quit at anytime please type \"Q\". Enter point:");
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
if (scan.hasNextInt()) {
System.out.println("Int input" + scan.nextInt());
} else {
String input = scan.next();
if (input.equalsIgnoreCase("Q")){
System.out.println("Exiting");
break;
}else {
System.out.println("You did not enter a valid value. Please enter a number or \"Q\" to quit.");
}
}
}
} catch (Exception e) {
System.out.println("Exiting Program.");
}
}
}
关于java - 要求输入整数,如果是 q 则退出,但如果有其他字母则重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47615428/