I've come across a little problem. How do I make it so that after my game is finished, I can choose whetever to exit my program or just restarting it from the beginning. In main method I've started my while loop to check my tries left if my counter is below 7 and I want to combine it , but I don't know how exactly My code so far :
public class Hangman {
public static String[] words = {"terminator", "banana", "computer", "cow", "rain", "water"};
public static String word = words[(int) (Math.random() * words.length)];
public String underscore = new String(new char[word.length()]).replace("\0", "_");
public int count = 0;
Scanner sc = new Scanner(System.in);
public void hang(String guess) {
String newstar = "";
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == guess.charAt(0)) {
newstar += guess.charAt(0);
} else if (underscore.charAt(i) != '_') {
newstar += word.charAt(i);
} else {
newstar += "_";
}
}
if (underscore.equals(newstar)) {
count++;
hangmanImage();
} else {
underscore = newstar;
}
if (underscore.equals(word)) {
System.out.println("Correct! You win! The word was " + word);
}
}
public void hangmanImage() {
if (count == 1) {
System.out.println("You have 6 tries left");
}
if (count == 2) {
System.out.println("You have 5 tries left");
}
if (count == 3) {
System.out.println("You have 4 tries left");
}
if (count == 4) {
System.out.println("You have 3 tries left");
}
if (count == 5) {
System.out.println("You have 2 tries left");
}
if (count == 6) {
System.out.println("You have 1 tries left");
}
if (count == 7) {
System.out.println("GAME OVER! The word was " + word);
}
}
}
public static void main(String[] args) {
Hangman hangman = new Hangman();
while (hangman.count < 7 && hangman.underscore.contains("_")) {
System.out.println("Guess any letter in the word");
System.out.println(hangman.underscore);
String guess = hangman.sc.next();
hangman.hang(guess);
}
}