I'm learning Java by trying to make a simple Rock-Paper-Scissors game in Eclipse:
package com;
import java.util.Random;
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Game game = new Game();
game.playerChoice();
game.aiChoice();
game.playGame();
}
public void playGame() {
if (playerChoice() == "Rock") {
if (aiChoice() == "Rock") {
System.out.println("Tie!");
} else if (aiChoice() == "Paper") {
System.out.println("AI wins!");
} else {
System.out.println("You win!");
}
} else if (playerChoice() == "Paper") {
if (aiChoice() == "Rock") {
System.out.println("You win!");
} else if (aiChoice() == "Paper") {
System.out.println("Tie!");
} else {
System.out.println("AI wins!");
}
} else {
if (aiChoice() == "Rock") {
System.out.println("AI wins!");
} else if (aiChoice() == "Paper") {
System.out.println("You win!");
} else {
System.out.println("Tie!");
}
}
}
public String playerChoice() {
Scanner scanner = new Scanner(System.in);
String word = null;
try {
System.out.println("Type Rock, Paper, or Scissors");
word = scanner.next();
System.out.println(word + " is saved as your choice");
} finally {
scanner.close();
}
return word;
}
public String aiChoice() {
String[] wordlist = {"Rock", "Paper", "Scissors"};
String word = wordlist [new Random().nextInt(wordlist.length)];
System.out.println("AI has randomly picked " + word);
return word;
}
}
When I input "Rock", "Paper", or "Scissors" in the scanner input I get the following in the console:
Type Rock, Paper, or Scissors
Rock <--- This is what I input into the console
Rock is saved as your choice
AI has randomly picked Scissors
Type Rock, Paper, or Scissors <--- This unintentionally repeats
Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Unknown Source)
at java.base/java.util.Scanner.next(Unknown Source)
at com.Game.playerChoice(Game.java:53)
at com.Game.playGame(Game.java:17)
at com.Game.main(Game.java:12)
What am I doing wrong that causes this exception and why does the System.out.println("Type Rock, Paper, or Scissors"); repeat itself? Thank you.