Reputation: 99
Want it to loop threw everything till the user put in the right number. When the user put in wrong number it should say "type in a different number". When the user put in the right number it should say "congrats you won". But till then it will loop and say "type in a different number" and after 5 tries I want it to say "you failed this mission! do you want to try again?"
import javax.swing.*;
import java.util.Random;
public class Projekt_1 {
public static void main(String[] args) {
String number;
JOptionPane.showMessageDialog(null, "Welcome to the guessing game!" + "\nYou gonna guess a number between 1 and 20." + "\nHOPE YOU LIKE IT!:)");
Random amount = new Random();
int guessnumber = anount.nextInt(20);
int random;
number = JOptionPane.showInputDialog("Guess a number between 1 and 20");
random = Integer.parseInt(number);
while (random == guessnumber){
JOptionPane.showMessageDialog(null, "You won!" + "\nYour number was" + "" + guessnumber);
}
if (random < guessnumber){
number = JOptionPane.showInputDialog("Your number is to high :(" + "\nType in a new lower number!");
random = Integer.parseInt(number);
}else if (random > guessnumber){
number = JOptionPane.showInputDialog("Your number is to low :(" + "\nType in a higher number!");
random = Integer.parseInt(number);
}
}
}
Upvotes: 0
Views: 117
Reputation: 17454
That is because your only iterative statement is only displaying "You won!..etc":
while (random == guessnumber){
JOptionPane.showMessageDialog(null, "You won!" + "\nYour number was" + "" + guessnumber);
}
Enclose the other codes below your while-loop to include them within the while loop. If you indent your codes properly, you should be able to spot your own problem. This is what you are looking for:
while (random != guessnumber){
//prompt for user input
if (random < guessnumber){
//Show Message "Your number is too low...
}
else if (random > guessnumber){
//Show Message "Your number is too high..."
}
else{ //got the number
//Show Message "you won!.."
}
}
Upvotes: 3