I'm trying to get user input and store the info (last name, first name, score) in an array for an object. But after getting the last name, the console prints the prompt to input the first name and then skips to the next method for the score, not letting me input anything for the first name.
However I tried moving the methods out of the for loop just to see if it worked and it did just fine. I feel that for some reason the Scanner is skipping to the next line while in the for loop.
This is the code in my main class:
int studentsNumber = Console.getInt("Number of students: ", 1, 500);
Student std[] = new Student[studentsNumber];
System.out.println("");
for (int i = 0; i < studentsNumber; i++) {
System.out.println(
"STUDENT " + (i + 1));
String lastName = Console.getString("Last Name: ");
String firstName = Console.getString("First Name: ");
int score = Console.getInt("Score: ", 0, 100);
std[i] = new Student(firstName, lastName, score);
}
The code on the Console class:
public class Console {
private static Scanner sc = new Scanner(System.in);
public static String getString(String prompt) {
String x = "";
boolean isValid = false;
while (!isValid) {
System.out.println(prompt);
if (sc.hasNextLine()) {
if (sc.hasNextInt() || sc.hasNextDouble()) {
System.out.println(
"Error! Invalid entry. Try again.");
sc.nextLine();
isValid = false;
} else {
x = sc.nextLine();
isValid = true;
}
} else {
System.out.println(
"Error! This entry is required. Try again.");
sc.nextLine();
isValid = false;
}
}
return x;
}
Edit: getInt() method in the Console class:
public static int getInt(String prompt, int min, int max) {
int x = 0;
boolean isValid = false;
while (!isValid) {
System.out.println(prompt);
if (sc.hasNextInt()) {
x = sc.nextInt();
isValid = true;
} else {
System.out.println(
"Error! Invalid integer. Try again.");
sc.nextLine();
isValid = false;
}
if (x < min) {
System.out.println(
"Error! Integer must be greater than " + min +
" Try again.");
sc.nextLine();
isValid = false;
} else if (x > max) {
System.out.println(
"Error! Integer must be less than " + max + " Try again.");
sc.nextLine();
isValid = false;
}
}
return x;
}