「Head First Java」という本からこのコードを練習していましたが、ここでのループの位置付けについてはかなり混乱しています。このコードはランダムなドットコムの単語を含む種類のゲームを作成するためのものです(例:abc .com)いくつかの配列要素を占めています。ここで私はそのドットコムの言葉に配列の3から5の位置を与え、ユーザーはその位置を推測しようとします。このコードをループに入れて、結果が "kill"になるまで毎回ユーザに入力するようにする方法はありますか?
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);
}
}
ああよく!これは私を攻撃しなかった!迅速な対応に感謝! :) –