I’m new in programming. I was building a rock paper scissors game. I got this problem. How do i restart it if user gives invalid choice. I tried restart();
command but nothing happens.
Scanner sc = new Scanner(System.in);
System.out.println("Hey player enter your name");
String name = sc.nextLine();
name = name.toLowerCase();
int human_score=0;
int pc_score=0;
System.out.println("How many rounds u want to play "+name);
byte rounds = sc.nextByte();
if (rounds>10){
System.out.println("Please choose up to 10 rounds. Above is not allowed");
System.out.println("Exiting the game");
System.exit(0);
}
int i =1;
while (i<=rounds) {
Random rand = new Random();
int pc = rand.nextInt(3);
pc += 1;
// System.out.println(pc);
System.out.println("What u choose?");
int human = sc.nextInt();
switch (human) {
case 1 -> System.out.println("You choose rock");
case 2 -> System.out.println("You choose paper");
case 3 -> System.out.println("You choose scissors");
default -> {
System.out.println("Invalid Choice");
}
}
switch (pc) {
case 1 -> System.out.println("I choose rock");
case 2 -> System.out.println("I choose paper");
case 3 -> System.out.println("I choose scissors");
}
if (human == pc) {
System.out.println("Its a draw");
} else if (human == 1 && pc == 2) {
System.out.println("You lost. Better luck next time");
pc_score+=1;
} else if (human == 1) {
System.out.println("Congrats. You won.");
human_score+=1;
} else if (human == 2 && pc == 1) {
System.out.println("Congrats. You won.");
human_score+=1;
} else if (human == 2) {
System.out.println("You lost. Better luck next time");
pc_score+=1;
} else if (human == 3 && pc == 1) {
System.out.println("You lost. Better luck next time");
pc_score+=1;
} else if (human == 3) {
System.out.println("Congrats. You won.");
human_score+=1;
}
i+=1;
}
if (human_score==pc_score){
System.out.println("Its a draw. Wanna play again?");
} else if(human_score>pc_score){
System.out.println("Congrats you won. Wanna challenge again?");
}else System.out.println("Skill issue. This code is fine");
System.out.println("PCt"+name+"n"+pc_score+"t"+human_score);
So, if someone enters a invalid choice I want it to restart the loop, like try again. I couldn’t find any way to do that(I am new, so don’t know about all methods). Can u help me
New contributor
Tomu is here is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.