I am instructed to skip a value if it has been guessed correctly so that it can proceed to ask for the other value without being repeated. I am only beginning to learn Java and have yet to learn how to do this. I tried to search up how to skip the correct guessed value but could not find anything. Is there a way to do this? Thank you in advance.
while (guessX != randomX || guessY != randomY) {
System.out.print("Enter a guess for the X position of Mr. Yertle: ");
guessX = scan.nextInt();
if (guessX < randomX) {
System.out.println("Too low! Guess higher.");
} else if (guessX > randomX) {
System.out.println("Too high! Guess lower.");
} else {
System.out.println("Ding, ding! You are correct!");
}
System.out.print("Enter a guess for the Y position of Mr. Yertle: ");
guessY = scan.nextInt();
if (guessY < randomY) {
System.out.println("Too low! Guess higher.");
} else if (guessY > randomY) {
System.out.println("Too high! Guess lower.");
} else {
System.out.println("Ding, ding! You are correct!");
}
CodePudding user response:
Split them to 2 parts.
while (guessX != randomX) {
System.out.print("Enter a guess for the X position of Mr. Yertle: ");
guessX = scan.nextInt();
if (guessX < randomX) {
System.out.println("Too low! Guess higher.");
} else if (guessX > randomX) {
System.out.println("Too high! Guess lower.");
} else {
System.out.println("Ding, ding! You are correct!");
}
}
while (guessY != randomY) {
System.out.print("Enter a guess for the Y position of Mr. Yertle: ");
guessY = scan.nextInt();
if (guessY < randomY) {
System.out.println("Too low! Guess higher.");
} else if (guessY > randomY) {
System.out.println("Too high! Guess lower.");
} else {
System.out.println("Ding, ding! You are correct!");
}
}
CodePudding user response:
You can break them into separate functions and check if you already has 1 correct value;
public static void feedback(int guess, int ans) {
if (guess < ans) {
System.out.println("Too low! Guess higher.");
} else if (guess > ans) {
System.out.println("Too high! Guess lower.");
} else {
System.out.println("Ding, ding! You are correct!");
}
}
public static int takeInput(char c) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a guess for the " c " position of Mr. Yertle: ");
return scan.nextInt();
}
public static void main(String[] args) {
int randomX = 10, randomY = 20;
int guessX = 0, guessY = 0;
while (guessX != randomX && guessY != randomY) {
guessX = takeInput('X');
feedback(guessX, randomX);
guessY = takeInput('Y');
feedback(guessY, randomY);
}
if(guessX == randomX) {
while(guessY != randomY){
guessY = takeInput('Y');
feedback(guessY, randomY);
}
}
else {
while(guessX != randomX){
guessX = takeInput('X');
feedback(guessX, randomX);
}
}
}