import java.util.Random;
import java.util.Scanner;
public class addinggamedowhile
{
public static void main (String[]args)
{
Random r = new Random ();
Scanner s = new Scanner(System.in);
int x = r.nextInt(20)+1;
int y = r.nextInt(20)+1;
int sum = x + y;
int guess;
System.out.println("===========");
System.out.println("Adding Game");
System.out.println("===========");
System.out.println();
int tries = 0;
for (int games = 0; games < 10; games++)
{
do
{
System.out.print (x + " + " + y + " = ");
guess = s.nextInt();
if (guess != sum && tries < 2)
{
System.out.println("Not quite. Try again!");
System.out.println();
tries++;
}
else
System.out.println("Not quite. The answer is " +sum+ ".");
System.out.println();
}
while (guess != sum);
System.out.println("Congratulations. You got it!");
System.out.println();
}
}}
我在这个循环中遇到了麻烦。我无法让循环在我想要的时候终止。它应该只持续十次“猜测”。另外,当用户答对问题时,我的else语句也会被执行。另一件事是,一旦用户答对了问题,或者在允许的 3 次内没有答对问题,就会出现一组新的数字。我也无法让它正确执行。我尝试了不同的效果很好的方法,但该项目的要求是使用 do while 循环。