我正在编写一个简单的模拟作为我研究的一部分(是的,我只是Java的初学者)。在其中我通过扫描仪从用户那里获取输入,我想检查输入是否有效格式(仅限数字)和有效范围。我遇到了困难 - 输入值不是来自“while”循环。你能给我一个提示吗?我会很感激的!
以下是您可能感兴趣的代码的一部分:
// check for invalid input
String input;
boolean valid = false;
while (!valid){
try{
input = sc.next();
user = Integer.parseInt(input);
valid = true;
}catch (NumberFormatException ex) {
System.out.println(ex);
System.out.println("Number but not a character or a symbol!");
}
System.out.println("Try once more!");
}
// interaction with user;
while (user !=3){
if (user ==1){
System.out.println("What angle I should set?");
userChange = sc.nextDouble();
shot.userAngle(userChange);
shot.show();
}
else if (user ==2){
System.out.println("What speed I should set?");
userChange = sc.nextDouble();
shot.userSpeed(userChange);
shot.show();
}
else {
System.out.println("Wrong number!");
}
System.out.println("What you want to change?");
user = sc.nextInt();
}
它表示可能未设置变量“user”。
答案 0 :(得分:0)
SOLED。这里的工作代码
int user;
double userChange;
boolean stop = false;
// check for invalid input if not integer and if out of range
// interaction with user
while (!stop){
try {
System.out.println("What you want to change?");
user = sc.nextInt();
if (user ==3){
stop = true;
}
while (user !=3){
if (user ==1){
System.out.println("What angle I should set?");
userChange = sc.nextDouble();
shot.userAngle(userChange);
shot.show();
}
else if (user ==2){
System.out.println("What speed I should set?");
userChange = sc.nextDouble();
shot.userSpeed(userChange);
shot.show();
}
else {
System.out.println("Wrong number!");
}
System.out.println("What you want to change?");
user = sc.nextInt();
if (user ==3){
stop = true;
}
}
}
catch (InputMismatchException e){
System.out.println(e);
System.out.println("Wrong input! Number but not a symbol or a character!");
sc.next();
}
}