Rachna Balani Rachna Balani - 5 months ago 12
Java Question

How to get this piece of code into loop, so that it asks a user input each time until the result is "kill"?

I was practicing this piece of code from the book 'Head First Java' and I'm quite confused on the positioning of the loop here.The code is for creating a kind of game that has a random dotcom word(ex: abc.com) occupying some array elements. here I gave that dotcom word the positions from 3 to 5 in the array, and the user tries guessing the position.

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);
}
}

Answer

You are allowed to declare the variable before initializing it:

String answer;
do {
  answer = sampleObj.checkForDotcom(userGuess);
  System.out.println(answer);
} while (!answer.equals("kill");

Also beware of the semantics of Scanner.nextInt(): if it can't parse the input as an int (for example, it contains letters), it will throw an exception, but won't jump over the invalid input. You'll have to use Scanner.nextLine() to force-jump over it, otherwise you'll get an infinite loop.

Comments