This is my first time posting. I'm taking my first programming class and am having an issue. My IDE doesn't show any bugs but when I run this code, it's not running past the user input for name. I get this error...
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at LAB.getString(LAB.java:38)
at LAB.getInteger(LAB.java:46)
at LAB.main(LAB.java:13)"
It's after the user is asked to input their name, it will re-ask the question and give me the above error message. I'm still very new to this and don't understand. Here's the code. Also, That whole piece of code is supposed to set the input to the variable "userName" but it won't let me use "userName" anywhere, why? Any help is very much appreciated.
import java.util.Random;
import java.util.Scanner;
public class LAB {
public static void main(String[] args) {
// Declare Variables
int number = 0;
int answer = 0;
int difference = answer - number;
// Call Modules
welcomeMessage();
getString();
getInteger();
// If number is less than 0, return error and exit program
if (number < 0) {
System.out.println("Error");
System.exit(0);
}
// Call Modules
randomNumber();
displayResult(answer, number, difference);
goodbyeMessage();
}
// Welcome Message Module
public static void welcomeMessage() {
System.out.println("*** WECOME TO THE TOY STORY ALIEN GUESSER GAME ***");
System.out.println("You must guess the number of Toy Aliens in the Gumball...);
}
// Get Username Module
public static String getString() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Contestant Name?: ");
String userName = keyboard.nextLine();
keyboard.close();
return userName;
}
// Get User Guess Module
public static int getInteger() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Ok " + getString() + ", How many Aliens do you think are...);
int number = keyboard.nextInt();
keyboard.close();
return number;
}
// Generate Random Number Module
public static int randomNumber() {
Random rand = new Random();
final int MAX = 1000;
int answer = rand.nextInt(MAX) + 1;
return answer;
}
// Display the Result
public static void displayResult(int answer, int number, int difference) {
if (answer == number) {
System.out.print("Great Guess! Are you a Psychic? That is the exact number of");
System.out.print("Aliens...YOU WIN");
}
else {
System.out.print("Good Try " + getString() + ", But there are actually ");
System.out.print("+ answer + " Aliens in the Gumball Machine. You were off");
System.out.print("by " + difference + ".");
}
}
// Goodbye Message
public static void goodbyeMessage() {
System.out.println("Thank you for playing.");
}
}