我正在练习“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/