Как эффективно использовать переменную счетчика для подсчета количества баллов? - PullRequest
2 голосов
/ 05 мая 2020

Я создаю игру ** угадывание слов *

Player1 вводит загадочное слово, а затем выводит количество букв в этом слове.

Затем в , в то время как l oop, player2 угадывает слова, и если они не являются загадочным словом, тогда в утверждении говорится: "фраза не является загадочным словом ", Но , когда player2 угадает загадочное слово, на выходе должно получиться следующее, как показано в операторах печати ниже:

else if (phrase.equals(mysteryphrase)){
    go = false;
    counter--;
    int points = (mysteryphrase.length()*10-counter*5);
    System.out.println("Correct! The mystery word is"+mysteryphrase+".");
    System.out.println("You made "+counter+" incorrect guesses");
    System.out.println("You get "+points+" points");

Я заставил его работать, но затем другой Требование состоит в том, что когда он достигнет двойной длины загадочного слова, игра должна остановиться и сказать следующее:

else if (counter2 == mysteryphrase.length()*2){
    go = false;
    System.out.println("\n"+"You made "+counter2+" incorrect guesses");
    System.out.println("You get 0 points");
    System.out.println("You lost the game");
} 

Проблема, с которой я столкнулся, заключается в том, что существует определенная формула для подсчета очков Это:

Points = (number of letters in the word * 10 - incorrect guesses *5)

Это работает, когда игра останавливается после удвоения длины загадочного слова, но когда player2 правильно угадывает загадочное слово, это не работает. Почему?

Для заинтересованных это весь мой код:

import java.util.Scanner;
public class Wordguess{
public static void main(String[]args){
Scanner keyboard = new Scanner(System.in);
    int option = Integer.parseInt(keyboard.nextLine());
    String mysteryphrase = keyboard.next();
        System.out.print("The mystery word has "+mysteryphrase.length()+" letters"+".");
        if (option == 1){
            boolean go = true;
            while (go){
                String phrase = keyboard.next();
                if (!phrase.equals(mysteryphrase)){
                    System.out.print("The mystery word is not "+phrase+".");
                }
                else if (phrase.equals(mysteryphrase)){
                    go = false;
                    System.out.print("Correct! The mystery word is "+mysteryphrase+".");
                }
            }
        }
        else if (option == 2){
            int counter = 1;
            boolean go = true;
            while (go){
                String phrase = keyboard.next();
                if (!phrase.equals(mysteryphrase)){
                    System.out.print("The mystery word is not "+phrase);
                    counter++;
                }
                else if (phrase.equals(mysteryphrase)){
                    go = false;
                    counter--;
                    int points = (mysteryphrase.length()*10-counter*5);
                    System.out.println("Correct! The mystery word is"+mysteryphrase+".");
                    System.out.println("You made "+counter+" incorrect guesses");
                    System.out.println("You get "+points+" points");
                }
            }
        }
        else if (option == 3){
            int counter = 1;
            int counter2 = 0;
            boolean go = true;
            while (go){
                String phrase = keyboard.next();
                if (!phrase.equals(mysteryphrase)){
                    System.out.print("The mystery word is not "+phrase);
                    counter++;
                    counter2++;
                }
                else if (phrase.equals(mysteryphrase)){
                    go = false;
                    counter--;
                    int points = (mysteryphrase.length()*10-counter*5);
                    System.out.println("Correct! The mystery word is"+mysteryphrase+".");
                    System.out.println("You made "+counter+" incorrect guesses");
                    System.out.println("You get "+points+" points");
                }
                else if (counter2 == mysteryphrase.length()*2){
                    go = false;
                    System.out.println("\n"+"You made "+counter2+" incorrect guesses");
                    System.out.println("You get 0 points");
                    System.out.println("You lost the game");
                } 
            }
        }
    }
}

Как вы можете видеть, я использовал два счетчика, один для выигрыша, а другой для проверки загадочных слов длина удваивается, и игра заканчивается. "counter", похоже, не работает для очков, когда player2 угадывает правильно.

Следующее является моим результатом, который неверен для очков:

You get 5 points

Это должно быть, скажем, после того, как игроки угадали правильно и после 5 угадываний:

You get 70 points

Ответы [ 3 ]

1 голос
/ 05 мая 2020

Если пользователь вводит 3 в качестве опции , у вас будет следующий код

if (!phrase.equals(mysteryphrase)){

Тогда у вас будет

else if (phrase.equals(mysteryphrase)) {

, после чего у вас будет

else if (counter2 == mysteryphrase.length()*2){

Вы никогда не введете последний else if. Либо слово, которое вводит пользователь, является загадочным, либо это не так. Третьего варианта нет. Возможно, вам просто нужно отбросить последнее else и сделать его

if (counter2 == mysteryphrase.length()*2){

EDIT

На самом деле вам нужно проверять значение counter2 сразу после каждого неправильного предположения, поэтому ваше начальное состояние должно быть

if (!phrase.equals(mysteryphrase)){
    System.out.print("The mystery word is not "+phrase);
    counter++;
    counter2++;
    if (counter2 == mysteryphrase.length()*2){
        go = false;
        System.out.println("\n"+"You made "+counter2+" incorrect guesses");
        System.out.println("You get 0 points");
        System.out.println("You lost the game");
    } 
}
0 голосов
/ 05 мая 2020

Следующий код никогда не будет выполнен в вашей программе:

else if (counter2 == mysteryphrase.length()*2){
    go = false;
    System.out.println("\n"+"You made "+counter2+" incorrect guesses");
    System.out.println("You get 0 points");
    System.out.println("You lost the game");
}

Причина в том, что когда вы проверяете, if (!phrase.equals(mysteryphrase)), он будет либо true, либо false и, следовательно, else if не только бессмысленно, но также может вызвать путаницу и проблемы, с которыми вы столкнулись.

Правильная программа:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter option: ");
        int option = Integer.parseInt(keyboard.nextLine());
        System.out.print("Enter the mystery word: ");
        String mysteryphrase = keyboard.next();
        System.out.println("The mystery word has " + mysteryphrase.length() + " letters.");
        if (option == 1) {
            boolean go = true;
            while (go) {
                System.out.print("Your word: ");
                String phrase = keyboard.next();
                if (!phrase.equals(mysteryphrase)) {
                    System.out.println("The mystery word is not '" + phrase + "'.");
                } else {
                    go = false;
                    System.out.print("Correct! The mystery word is '" + mysteryphrase + "'.");
                }
            }
        } else if (option == 2) {
            int counter = 1;
            boolean go = true;
            while (go) {
                System.out.print("Your word: ");
                String phrase = keyboard.next();
                if (!phrase.equals(mysteryphrase)) {
                    System.out.println("The mystery word is not " + phrase);
                    counter++;
                } else {
                    go = false;
                    counter--;
                    int points = mysteryphrase.length() * 10 - counter * 5;
                    System.out.println("Correct! The mystery word is '" + mysteryphrase + "'.");
                    System.out.println("You made " + counter + " incorrect guesses.");
                    System.out.println("You get " + points + " points.");
                }
            }
        } else if (option == 3) {
            int counter = 1;
            int counter2 = 0;
            boolean go = true;
            while (go) {
                System.out.print("Your word: ");
                String phrase = keyboard.next();
                if (!phrase.equals(mysteryphrase)) {
                    System.out.println("The mystery word is not '" + phrase + "'.");
                    counter++;
                    counter2++;
                } else {
                    if (counter2 == mysteryphrase.length() * 2) {
                        System.out.println("\n" + "You made " + counter2 + " incorrect guesses.");
                        System.out.println("You get 0 points");
                        System.out.println("You lost the game");
                        break;
                    }
                    go = false;
                    counter--;
                    int points = mysteryphrase.length() * 10 - counter * 5;
                    System.out.println("Correct! The mystery word is '" + mysteryphrase + "'.");
                    System.out.println("You made " + counter + " incorrect guesses.");
                    System.out.println("You get " + points + " points.");
                }
            }
        }
    }
}

Пробный запуск:

Enter option: 1
Enter the mystery word: hello
The mystery word has 5 letters.
Your word: hi
The mystery word is not 'hi'.
Your word: bye
The mystery word is not 'bye'.
Your word: hello
Correct! The mystery word is 'hello'.

Другой прогон образца:

Enter option: 2
Enter the mystery word: hello
The mystery word has 5 letters.
Your word: hi
The mystery word is not hi
Your word: bye
The mystery word is not bye
Your word: hello
Correct! The mystery word is 'hello'.
You made 2 incorrect guesses.
You get 40 points.

Другой прогон образца:

Enter option: 3
Enter the mystery word: hello
The mystery word has 5 letters.
Your word: hi
The mystery word is not 'hi'.
Your word: bye
The mystery word is not 'bye'.
Your word: hello
Correct! The mystery word is 'hello'.
You made 2 incorrect guesses.
You get 40 points.

Другой прогон образца:

Enter option: 3
Enter the mystery word: hi
The mystery word has 2 letters.
Your word: hello
The mystery word is not 'hello'.
Your word: world
The mystery word is not 'world'.
Your word: bye
The mystery word is not 'bye'.
Your word: moon
The mystery word is not 'moon'.
Your word: hi

You made 4 incorrect guesses.
You get 0 points
You lost the game
0 голосов
/ 05 мая 2020

Более короткий и простой код для вашей программы:

import java.util.*;
public class GFG{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the mystery word");
        String mystery=sc.nextLine();
        int counter=0;
        while(counter<mystery.length()*2){
            System.out.println("Guess the mystery word!");
            String guess=sc.nextLine();
            if(guess.equals(mystery))
                break;
            counter++;
        }
        if(counter==mystery.length()*2)
            System.out.println("You made "+counter+" incorrect guesses so your score is 0");
        int score=mystery.length()*10-counter*5;
        System.out.println("You made "+counter+" incorrect guesses and your score is "+score);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...