简体   繁体   English

任何人都可以帮助我解释为什么我的Java方法不能完全按照我的期望去做吗?

[英]Could anyone help me with why my Java method isn't quite doing what I'm expecting it to do?

For a class project, we have to create a hangman game in Java (we're starting off with object oriented programming, so this is getting us used to it) and I have the class file then the main file. 对于一个类项目,我们必须用Java创建一个刽子手游戏(我们从面向对象编程开始,所以这让我们习惯了)并且我有类文件然后是主文件。

Everything's working great, but I want one of my methods in the class file to tell the player if they've already guessed a particular character. 一切都很好,但是我想在类文件中使用我的一个方法来告诉玩家他们是否已经猜到了一个特定的角色。

Basically, the method uses a for loop to add the guessed characters into a character array, and every time the player guesses it checks to see if that character is there (if it is, it breaks out of the loop) and if not, and the index value is 0 (this means it's unwritten, right?) it will write the character that was guessed to that index value. 基本上,该方法使用for循环将猜测的字符添加到字符数组中,并且每次玩家猜测它都会检查该字符是否存在(如果是,它会突破循环),如果没有,则索引值是0(这意味着它是不成文的,对吧?)它会写出猜测到该索引值的字符。

The only other thing that I don't think is self explanatory in the code, is that if the player has yet to make any guesses, it makes the first value the guess, so it has something to start with in the array. 我认为在代码中唯一不自觉的另一个问题是,如果玩家还没有做出任何猜测,那么第一个值就是猜测,所以它在数组中有一些东西可以开始。

Any help would be appreciated, and if anyone has any input on how to improve my code or whatever, I'd be happy to hear that as well. 任何帮助将不胜感激,如果任何人有任何关于如何改进我的代码或任何其他的意见,我也很高兴听到这一点。 Thanks so much. 非常感谢。 :) :)

public void makeGuess(char c) { 
    boolean alreadyGuessed = false, anyMatches = false;
    matches = 0;
    guesses++;
    if (guesses == 1) {
        guessedChars[0] = c;
    }
    for (int i = 0; i < guessedChars.length; i++) { //it goes through it and will see that it was already guessed
        if (guessedChars[i] == c) {
            alreadyGuessed = true;
            break;
        }
        else if (guessedChars[i] != c && guessedChars[i] == 0) {
            guessedChars[i] = c;
        }
    }

    if (alreadyGuessed == false) {
        for (int i = 0; i < word.length; i++) {
            if (word[i] == c) {
                anyMatches = true;
                matches++;
                disguisedWord[i] = c;
            }
        }
    }       
    if (anyMatches == true) {
        System.out.println("You guessed correctly!");
        System.out.println("There were " + matches + " matches.");
    }
    else if (alreadyGuessed == true) {
        System.out.println("You already guessed this letter, derp.");
    }
    else {
        System.out.println("Sorry, that character is not in the word to be guessed.");
        wrongGuesses++;
    }
//      for (int i = 0; i < guessedChars.length; i++) {
//          System.out.print(guessedChars[i] + " "); 
//      }       
    }

MAIN METHOD: 主要方法:

import java.util.Scanner;
class HangmanDemo {
    public static void main(String[] args) {
        //Object initialization
        Scanner keyboard = new Scanner(System.in);
        Hangman word = new Hangman("jordan");

        //Variable declaration
        char letterGuess;
        int limit;

        //Interact with user
        System.out.print("What would you like the limit of guesses to be: ");
        limit = keyboard.nextInt();

        //BEGIN ZE GAME
        while (word.isFound() == false && word.getWrongGuessCount() <= limit) {
            System.out.println();
            System.out.print("Letter guess: ");
            letterGuess = keyboard.next().charAt(0);
            word.makeGuess(letterGuess);
            System.out.println(word.getDisguisedWord());
        }
        if (word.getGuessCount() == limit) {
            System.out.println("\nSorry, too many guesses.");
        }
        else {
            System.out.println("\nCongratulations! You succesfully solved the word!");
        }
    }
}

So, check this out: 所以,看看这个:

First time you call the method, both alreadyGuessed and and anyMatches will stay false... and that's obviously not good. 第一次调用方法时,已经猜到的和任何匹配都会保持错误......这显然不是很好。

Second: OOP is NOT procedural P. More concretely: a method is not supposed to do as many things as you do. 第二:OOP不是程序性的P.更具体地说:一种方法不应该像你一样做很多事情。 A method should have a lot of explaining to do it if plans to be larger than 10 lines. 如果计划大于10行,方法应该有很多解释。 That's so full of language constructs you can't go over it fast. 这是如此充满语言结构,你无法快速完成它。 Split your code... less local variables, more methods. 拆分你的代码...更少的局部变量,更多的方法。

Hope that helps. 希望有所帮助。

跟踪猜测的一种方法是使用布尔值或字符数组(对应于猜测的基数字母; a = 0,b = 1等)。

The main problem I'm seeing is in your looping logic. 我看到的主要问题是你的循环逻辑。

This will always be true the first time because guessedChars[0] will be equal to the first entry added and you add the first entry before checking if a letter was guessed. 这将是第一次真实,因为guessedChars [0]将等于添加的第一个条目,并且在检查是否猜到了一个字母之前添加了第一个条目。

    if (guessedChars[i] == c) {
        alreadyGuessed = true;
        break;
    }

Also, you don't tell us how guessedChars[] is defined. 另外,您没有告诉我们如何定义guessedChars []。 Depending on how you did this you might have problems with the whole thing given that the loop is driven off of guessedChars.length and assuming that an unassigned value would be 0. The big thing I notice is that you don't break after you have determined that the letter has not yet been guessed. 根据你如何做到这一点你可能会遇到整个事情的问题,因为循环是从guessedChars.length驱动的,并假设未分配的值是0.我注意到的最重要的事情是你没有破坏确定这封信还没有被猜到。 You at a minimum need to do this otherwise all other elements after guessedChars[i] will also be set to that guessed letter. 您至少需要这样做,否则guessedChars [i]之后的所有其他元素也将设置为该猜测的字母。 I do recommend perhaps using a different type of loop though. 我建议也许使用不同类型的循环。

bool searchingForLetter = true;
do
{
    //.... Your Logic
    //.... searchingForLetter = false when you have either found the letter 
    //.... or placed the letter in the array
    //.... or reached the end of the array
} while(searchingForLetter)

One possible solution is to use the integer value of an char , because every letter is represented by a number. 一种可能的解决方案是使用char的整数值,因为每个字母都由数字表示。 For the ANSI-Standard it is useful to know, that the common letters starting a number 65 for 'A' up to 90 for 'Z'. 对于ANSI标准,有用的是知道,'A'的公共字母从数字65开始,对于'Z'从90开始。 From 97 up to 122 you will find the small letters. 从97到122你会发现小写字母。

You need a boolean array of 25, every value stand for one letter. 你需要一个25的布尔数组,每个值代表一个字母。 Here is some code to demonstrate the functionality: 以下是一些演示功能的代码:

    boolean[] guessedChars = new boolean[25];
    char[] test = "HELLO".toCharArray();

    for (char element : test) {
        System.out.println(element);
        System.out.println((int) element);
        if (guessedChars[element - 65] == false) {
            guessedChars[element - 65] = true;
        } else {
            System.out.println("You already guessed this letter, derp.");
        }
    }

'Hello' is the example string, to get the right position in the array you have to substract 66 from the element integer value. 'Hello'是示例字符串,要在数组中获得正确的位置,您必须从元素整数值中减去66。 An 'A' with the value of 65 will be stored in guessedChars[0]. 值为65的“A”将存储在guessedChars [0]中。 It is easy to extend for small letters for the hangman game, because you can changed the String to upper case with the toUpperCase() -method before checking. 对于刽子手游戏来说,很容易为小写字母进行扩展,因为在检查之前你可以使用toUpperCase()方法将String更改为大写。

暂无
暂无

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

相关问题 为什么 Swing 框架有时没有在下面打开我附加了我的代码,任何人都可以帮助我为什么会这样? - Why Swing frame isn't opening sometimes below I attached my code and anyone help me why is it happening? 我正在尝试通过Java书籍中的练习来编写一些程序,但并没有完全了解我的要求 - I'm trying to program something from an exercise in my Java Book, not quite getting what is being asked of me 遇到找不到或无法加载主类错误的情况,有人可以帮助我修复该错误吗? 我是Java新手 - Getting a could not find or load main class error, can anyone help me fix it? I'm new to java 谁能告诉我我在做什么错? -堆栈 - Can anyone tell me what I'm doing wrong? - Stacks 我该如何避免这种情况的发生,为什么我已经在做的事情不起作用? - How do I stop this from going out of bounds, and why isn't what I'm already doing working? 我无法在程序中使用PrinterWriter,有人可以帮我解决吗? - I can't use PrinterWriter in my program, could anyone help me figure it out? 有一种有效的“合并排序”功能,但不是完全可以,有人可以告诉我我做错了什么吗? - Have a sort of working Merge Sort, but not quite, could someone tell me what I am doing wrong? 我的 isEmpty 方法不起作用,我不知道为什么 - My isEmpty method isn’t working and I'm not sure why 我的外键没有插入数据库,知道我在做什么错吗? - My foreign key isn't being inserted into the database, any idea what I'm doing wrong? 谁能告诉我为什么我的程序不起作用? - Could anyone tell me why my program doesn't work?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM