For a project I have to make to hangman game. Everything works but I'm trying make a loop which lets the user play again if he/she chooses.
import java.util.Scanner;
//this is the main method where I'm trying to add the loop//
public class hangMan {
public static void main(String[] args) {
String repeat = "y";
while (repeat == "y") {
Scanner sc = new Scanner(System.in);
String w = randomWord("cat", "kite", "touch", "yellow", "abdomen");
if (w.equals("cat")) {
threeword();
}
if (w.equals("kite")) {
fourword();
}
if (w.equals("touch")) {
fiveword();
}
if (w.equals("yellow")) {
sixword();
}
if (w.equals("abdomen")) {
sevenword();
}
System.out.println("Do you want to play again? (y/n): ");
repeat = sc.next();
sc.close();
}
}
I was expecting for the loop to keep repeating the game if the user entered "y" for repeat and for the game to stop if the user entered any other character. However, instead I keep getting a java.util.NoSuchElementException error. I would appreciate if anyone can help me create a loop and explain to me why what I did to mess up. Thank you