I'm working on a small game project that requires me to do some simple I/O through the java console. The function below should take three inputs separated by spaces. Unfortunately a problem occurs when I try to scan the user input.
public static String[] getVals(Board game)
{
Scanner scan = new Scanner(System.in);
boolean canPlace = true;
String [] inputs;
do
{
System.out.println("Please input your choice\n");
String input = scan.nextLine();
inputs = input.split(" ");
if(inputs.length == 3)
{
if(game.setVal(inputs))
{
canPlace = true;
}
}
else if(inputs[0].equalsIgnoreCase("quit"))
{
quit();
}
else
{
System.out.println("That is not a valid play. Please try again.");
canPlace = false;
}
}while(!canPlace);
scan.close();
return inputs;
}
This is what is thrown when I call the getVals method:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at SOS.getVals(SOS.java:101)
I read user input in an earlier function in exactly the same way, and it worked correctly. I'm not sure if it is relevant to the problem, but here is the scan portion of that function:
public static void intro()
{
Scanner scan = new Scanner(System.in);
System.out.println("Please input the player 1's name.\n ");
Player Player1 = new Player(scan.nextLine());
System.out.println("Please input the player 2's name.\n ");
Player Player2 = new Player(scan.nextLine());
System.out.println("What size do you want your board (Min size is 3, Max is 10)");
int size = Integer.parseInt(scan.nextLine());
scan.close();
Thanks for any advice!