In my code there is a do while loop(the second one in my code.) that is immediately printing the else statement of my nested if else statement. After he printed the else statement the console asks for user input. The console should ask for user input immediately and should not print the else statement. Does anyone know what is wrong with my code?
public class Numberone {
public void numberone() {
Scanner input = new Scanner(System.in);
Random dice = new Random();
boolean error1;
boolean error2;
int number1;
int random;
int counter;
String Choice;
String Once;
String Win;
System.out.println();
System.out.println("Choose a number between 1 and 6.");
// number 1
do {
number1 = input.nextInt();
System.out.println();
error1 = 1 > number1 || number1 > 6;
switch(number1){
case 1:
System.out.println("You chose the number 1.");
break;
case 2:
System.out.println("You chose the number 2.");
break;
case 3:
System.out.println("You chose the number 3.");
break;
case 4:
System.out.println("You chose the number 4.");
break;
case 5: System.out.println("You chose the number 5.");
break;
case 6:
System.out.println("You chose the number 6.");
break;
default:
System.out.println("You didn't chose a number between 1 and 6, please choose again.");
}
} while(error1);
// game
System.out.println("Do you want to play once or untill you win?");
// this is the do while loop that is printing wrong. It is printing the else statement without asking for user input.
do {
System.out.println("To play once typ: Once. To play untill you win type: Win");
Choice = input.nextLine();
Once = "Once";
Win = "Win";
random = 1 + dice.nextInt(6);
counter = 0;
error2 = (! (Choice).equals(Win)) || (! (Choice).equals(Once));
if((Choice).equals(Win)){
for(counter=1;number1!=random;counter++){
random = 1 + dice.nextInt(6);
System.out.println("Roll " + counter + ".");
System.out.println("Your number is " + number1 + " The number of the dice is " + random);
if(number1 == random){
System.out.println("Congratulions you have won. Total rolls: " + counter + ".");
break;
}
}
}
else if((Choice).equals(Once))
if (random == number1){
System.out.println("The dice rolled: " + random);
System.out.println("Congratulations you've won");
} else {
System.out.println("The dice rolled: " + random);
System.out.println("You didn't win");
}
else {
System.out.println("This is not a valid answer. Please try again.");
}
} while(error2);
input.close();
}
}
Aucun commentaire:
Enregistrer un commentaire