最近,我一直在练习关于java的初学者教程, 但是我对if else声明感到困惑,
我主要关注的是让用户在用户尝试超过5次时写入,它将返回false,否则它将返回true。
任何帮助将不胜感激。
int userTry = 0;
double value1 = 0;
Scanner useranswer1 =new Scanner(System.in);
if(userTry == 5){
do{
System.out.println("What is 10 divided by 4?");
value1 = useranswer1.nextDouble();
}
while(value1 != 2.5);
System.out.println("You got the right answer");
} else {
} System.out.println("You have zero more tries");
}
答案 0 :(得分:3)
尝试以下方法:
int userTry = 0;
double value1 = 0;
Scanner useranswer1 =new Scanner(System.in);
for (int userTry = 5; userTry > 0; userTry--)
System.out.println("What is 10 divided by 4?");
value1 = useranswer1.nextDouble();
if (value1 == 2.5) break;
System.out.println(); // empty line
}
if (value1 == 2.5) {
System.out.println("You got the right answer");
} else {
System.out.println("You have zero more tries");
}
}
答案 1 :(得分:2)
关键是根据用户没有得到正确值的检查以及是否有足够的重试来设置do-while循环的条件。
如果用户获得了正确的值,他们已经按照所需的重试次数进行了操作,否则他们就会尝试零次。希望这会有所帮助。
int userTry = 0;
double value1 = 0.0;
Scanner useranswer1 = new Scanner(System.in);
do {
System.out.println("What is 10 divided by 4?");
value1 = useranswer1.nextDouble();
} while (value != 2.5 && ++userTry < 5); // NOTE: pre-increment and check. If you like to have a safer version, move this increment inside the while loop.
if (value1 != 2.5) {
System.out.println("You have zero more tries");
} else {
System.out.println("You got the right answer!");
}
答案 2 :(得分:2)
int count = 0;
double trueAnwer = 6.66;
while (true) {
count++;
Scanner useranswer1 =new Scanner(System.in);
if (trueAnwer == useranswer1.nextDouble()) {
System.out.println("You got the right answer");
return;
}
if (count==5) {
System.out.println("You have zero more tries");
return;
}
System.out.println("This is "+count+" times");
}
答案 3 :(得分:1)
试试这个:
do{
System.out.println("What is 10 divided by 4?");
value1 = useranswer1.nextDouble();
userTry++;
}
while(value1 != 2.5 && userTry != 5);
if(userTry == 5){
System.out.println("You have zero more tries");
} else {
System.out.println("You got the right answer");
}