简体   繁体   English

猜谜游戏Java

[英]Guessing Game Java

I'm writing a game which makes the user guess the number that is generated randomly.我正在编写一个游戏,让用户猜测随机生成的数字。 In the end it would show the total number correct and the sum of those correct numbers.最后,它会显示正确的总数和这些正确数字的总和。 However, I cannot show the right sum of the correct number that the user has.但是,我无法显示用户拥有的正确数字的正确总和。 Can someone help me with this?有人可以帮我弄这个吗? Thank you!谢谢!

public static void main(String[] args) {
    Random rng = new Random();
    Scanner consoleScanner = new Scanner(System.in);
    String inputString;
    int answer = rng.nextInt(90000) + 10000, sum, numberCorrect;
    System.out.print("I have randomly chosen a 5-digit code for you to guess.\n"
            + "Each time you guess, I will tell you how many digits are correct and the sum of the digits that are correct.\n"
            + "For example, if the number is \"68420\" and you guess 12468, I will respond:\n"
            + "Number of Digits Correct: 1\n" + "Sum of Digits Correct   : 4\n"
            + "From deduction, you will know the 4 was correct in the guess.\n\n"
            + "Now its your turn..................................................................\n" + "answer = "
            + answer);
    do {
        System.out.print("\nPlease enter a 5-digit code (your guess): ");
        inputString = consoleScanner.nextLine();
        numberCorrect = 0;
        sum = 0;
        if (inputString.length() != 5) {
            System.out.println("Please enter 5-digit code only.");
            System.exit(0);
        }
        for (int i = 0; i < 5; i++) {
            String answerString = String.valueOf(answer);
            if (inputString.charAt(i) == answerString.charAt(i)) {
                numberCorrect++;
                char digit = answerString.charAt(i);
                sum += digit;
            }
        }
        System.out.println("Number of Digits Correct: " + numberCorrect + "\nSum of Digits Correct:    " + sum);
    }
    while (numberCorrect < 5);
    System.out.println("****HOORAY!  You solved it.  You are so smart****");
}

Your sum variable is integer and you are trying to add it to char (digit).您的 sum 变量是整数,您正试图将其添加到 char(数字)中。 you need to convert the character to valid int and then add it to sum.您需要将字符转换为有效的 int,然后将其添加到 sum。

following references may help!以下参考资料可能会有所帮助!

Java: parse int value from a char Java:从字符解析 int 值

or或者

Converting characters to integers in Java Java中将字符转换为整数

您必须将字符转换为数值:

sum += Character.getNumericValue(digit);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM