如何使用while循环以及如何在循环中使用count

时间:2014-01-18 18:09:51

标签: java random

此程序旨在添加计算机生成的2个随机数,当用户答案出错时,计算机会通过使用while循环告诉用户再次尝试。一旦用户输入正确的号码,程序将停止。我必须在while循环中计算错误的计数,但是,当它是第二次尝试时,它给出了错误的计数1.请小心告诉我代码中出错的地方。谢谢。

import java.util.Scanner;

public class add {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        int num1 = (int) (Math.random() * 10);
        int num2 = (int) (Math.random() * 10);
        int wrong = 0;

        System.out.println("What is " + num1 + "+" + num2 + "=" + "?");
        int answer = input.nextInt();

        while (num1 + num2 != answer) {
            System.out.println("Wrong answer, Try again . " +
                    "What is  " + num1 + "+" + num2 + "? ");
            answer = input.nextInt();
            System.out.println("The number of attemt is " + wrong);
            ++wrong;
        }
        System.out.println("You got it correct !");
    }
}

5 个答案:

答案 0 :(得分:2)

错误在于增加用户在打印后出错的数字“你得x错了”

答案 1 :(得分:1)

只需将++wrong放在System.out.println("The number of attemt is " + wrong);

之上
while (num1 + num2 != answer) {
            System.out.println("Wrong answer, Try again . " +
                    "What is  " + num1 + "+" + num2 + "? ");
            answer = input.nextInt();
            ++wrong;
            System.out.println("The number of attemt is " + wrong);

        }

答案 2 :(得分:0)

wrong初始化为1而不是0。

int wrong = 1;

如果采用这种方法,变量的更合适的名称将是attempt

答案 3 :(得分:0)

只需更改

wrong = 0

wrong = 1

错误应该可以重命名为numberOfAttempts。

答案 4 :(得分:0)

在显示之前,您需要增加错误:

import java.util.Scanner;
public class Add {
    public static void main(String[] args ){
        Scanner input = new Scanner (System.in);

        int num1 = (int)(Math.random() * 10);
        int num2 = (int)(Math.random() * 10);
        int wrong = 0 ;

        System.out.println("What is " + num1 + "+" + num2 + "=" + "?");
        int answer = input.nextInt();

        while (num1 + num2 != answer){
            wrong++ ;
            System.out.println("Wrong answer, Try again . What is  " + num1 +"+"+ num2 + "? " );
            answer = input.nextInt();
            System.out.println("The number of attempt is " + wrong);

        }
        System.out.println("You got it correct !");
    }
}