简体   繁体   中英

“Why does my lottery game ignores zeros?”

I'm doing exercice 3 from Chapter 4 of the book "Introduction to Java" by Walter Savitch. Instructions: Develop an algorithm for a simple game of guessing at a secret five-digit code. When the user enters a guess at the code the program returns two values: the number of digits in the guess that are in the correct position and the sum of those digits. For example, if the secret code os 53840, and the user guesses 83241, the digits 3 and 4 are in the correct position. Thus, the program should respond 2 and 7. Allow the user to guess a fixed number of times

Current problems:

  • my code looks dirty and too long. I'm a beginner, but looking for ways to make it more efficient
  • when entering a 'guess number' that starts with any other number than 0 it works but when it starts with 0, my program ignores the first digit

I've spent two hours on it. There's still another 25 exercises waiting for me in this chapter only so I hope to be more efficient with the other exercises.

 public static void main(String[] args) {
        int SecretCode = 12140;
        int Win = 0;
        //just checking the incrementor
        int sum = 0;
        System.out.println("Ceci est un jeu de lotterie. \nPouvez-vous deviner le nombre à 5 chiffres caché ?\n");

        Scanner fromPlayer = new Scanner(System.in);
        do {
            System.out.println("Votre nombre porte-bonheur: ");
            int guess = fromPlayer.nextInt();
            //Interprets Guess int to string
            String stringGuess = String.valueOf(guess);
            int length = stringGuess.length();

            boolean CorrectLength = (length == 5);
            if (CorrectLength) {

                String Firstdigit = stringGuess.substring(0, 1);
                String Seconddigit = stringGuess.substring(1, 2);
                String Thirddigit = stringGuess.substring(2, 3);
                String Fourthdigit = stringGuess.substring(3, 4);
                String Fifthdigit = stringGuess.substring(4);

                //Interprets Secret Code int to string
                String stringSecretCode = String.valueOf(SecretCode);
                String FirstdigitCode = stringSecretCode.substring(0, 1);
                String SeconddigitCode = stringSecretCode.substring(1, 2);
                String ThirddigitCode = stringSecretCode.substring(2, 3);
                String FourthdigitCode = stringSecretCode.substring(3, 4);
                String FifthdigitCode = stringSecretCode.substring(4);

                //Just checking the values that the program will compare to secret code
                System.out.println("Vous avez entré \n" + Firstdigit + "\n" + Seconddigit + "\n" + Thirddigit + "\n" + Fourthdigit + "\n" + Fifthdigit);

                if (Firstdigit.equals(FirstdigitCode)) {
                    Win = Win + 1;
                    sum = sum + Integer.parseInt(Firstdigit);
                    System.out.println("Premier numéro est : correct. Score: " + Win);
                } else {
                    System.out.println("Premier numéro est : incorrect. Score:" + Win);

                }
                if (Seconddigit.equals(SeconddigitCode)) {
                    Win = Win + 1;
                    sum = sum + Integer.parseInt(Seconddigit);
                    System.out.println("Deuxième numéro est : correct. Score: " + Win);

                } else {
                    System.out.println("Deuxième numéro est : incorrect. Score: " + Win);

                }

                if (Thirddigit.equals(ThirddigitCode)) {
                    Win = Win + 1;
                    sum = sum + Integer.parseInt(Thirddigit);
                    System.out.println("Troisième numéro est : correct. Score: " + Win);

                } else {
                    System.out.println("Troisième numéro est : incorrect. Score: " + Win);

                }
                if (Fourthdigit.equals(FourthdigitCode)) {
                    Win = Win + 1;
                    sum = sum + Integer.parseInt(Fourthdigit);
                    System.out.println("Quatrième numéro est : correct. Score: " + Win);

                } else {
                    System.out.println("Quatrième numéro est : incorrect.  Score: " + Win);

                }
                if (Fifthdigit.equals(FifthdigitCode)) {
                    Win = Win + 1;
                    sum = sum + Integer.parseInt(Fifthdigit);
                    System.out.println("Cinquième numéro est : correct. Score: " + Win);

                } else {
                    System.out.println("Cinquième numéro est : incorrect.  Score: " + Win);

                }
                System.out.println("Vous avez deviné " + Win + " numéros. Leur total vaut " + sum);

            } else {
                System.out.println("ERREUR. Il faut entrer 5 chiffres.");
            }

I expect the output of 02140 to be "Premier numéro est: incorrect. Score: 0 Deuxième numéro est: correct. Score: 1 Troisième numéro est: correct. Score: 2 Quatrième numéro est: correct. Score: 3 Cinquième numéro est: correct. Score: 4 Vous avez deviné 4 numéros. Leur total vaut 7"

BUT the actual output is: ERREUR. Il faut entrer 5 chiffres. as if the program doesn't identify 0 as a digit.

Instead of using

String stringGuess = String.valueOf(guess);

you should use

String stringGuess = String.format("%05d", guess);

to always convert the number you've read into a five digit long String . In your current solution you should see that if you print stringGuess leading zeros will have been removed from the input.

Instead, you could use the following code which uses the nextLine() method of the Scanner class to solve your problem:

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

    char[] expected = "53849".toCharArray();

    // enter CTRL-D to stop
    while (scanner.hasNext()) {
        String input = scanner.nextLine();

        if (input.length() != 5) {
            System.err.println("wrong length");
            continue;
        }

        char[] actual = input.toCharArray();

        int digitSum = 0;
        int correctDigits = 0;

        for (int i = 0; i < expected.length; i++) {
            if (actual[i] == expected[i]) {
                correctDigits++;
                digitSum += actual[i] - '0';
            }
        }

        String msg = String.format(
                "Number of correct digits: %d, their sum: %d",
                correctDigits, digitSum
        );
        System.out.println(msg);
    }

Try the one below and see if it works for you. Take the input directly into stringGuess instead of taking it into int and then converting it into String.

int guess = fromPlayer.nextInt(); //remove this and take input into the below variable directly
String stringGuess = fromPlayer.next();

Check this for your reference why the int cannot store leading zeroes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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