java - 如何让这段代码进入循环,以便每次都询问用户输入,直到结果为 "kill"?

标签 java loops

我正在练习“Head First Java”一书中的这段代码,但我对此处循环的位置感到很困惑。该代码用于创建一种具有随机网络单词的游戏(例如: abc.com) 占用了一些数组元素。在这里,我给那个 dotcom 词指定了数组中从 3 到 5 的位置,然后用户尝试猜测该位置。

import java.util.Scanner;

public class RunTheGame {

    public static void main(String[] args) {

        MainGameClass sampleObj= new MainGameClass();
        int[] location = {3,4,5};
        sampleObj.setdotcomLocationCells(location);


        Scanner input= new Scanner(System.in);
        System.out.println("Enter your guess");
        int userGuess=input.nextInt();

        String answer = sampleObj.checkForDotcom(userGuess);
        System.out.println(answer);

    }
}

package simpleDotComGame;

public class MainGameClass {
    int[] DotcomLocationCells;
    int numOfHits=0;

    public void setdotcomLocationCells(int[] location) {
        DotcomLocationCells= location;
    }

    public String checkForDotcom(int userGuess) {
        String result="miss";
        for(int cell:DotcomLocationCells) {
            if(cell == userGuess) {
                result ="hit";
                numOfHits++;
                break;
            }
        } // end for loop

        if(numOfHits == DotcomLocationCells.length) {
            result = "kill";            
            System.out.println("The number of tries= "+numOfHits);
        }
}

最佳答案

do {
        <insert code where answer result is created>
} while (!answer.equals("kill"))

upd.: 但是您必须重写 equals 方法才能正确使用,因为如果您看到方法是如何在 Object.class 中声明的,您会发现

public boolean equals(Object obj) {
    return (this == obj);

关于java - 如何让这段代码进入循环,以便每次都询问用户输入,直到结果为 "kill"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38026936/

相关文章:

r - R Rvest for()和错误服务器错误: (503) Service Unavailable

javascript - 如何等到循环内的异步进程完成后再退出循环?

javascript - 如何使用 JavaScript 写入 html?

java - 如何捕获 JTA-Transaction 中抛出的异常?

java - 搜索字符串列表(100 000 个字符串): How to search for x character if there is a %

java - 在java中设置字节值

java - 在对象数组上使用 for-each - "Integer[] array"- 为什么 "for(int i : array)"有效?

excel - 执行直到循环以获取大于某个数字的单元格的值

java - 无限 while 循环,而 AsyncTask 未完成

java - android项目中的project.properties