In this script, the user must input 5 numbers separated by new lines. The purpose is to check whether the input is an integer or not, and if it isn't, then it should theoretically loop, asking the user to input a valid integer.
The first part works - if the user inputs a value which isn't an integer, it throws the error and asks them to input a valid integer. But if they enter an invalid integer again, it throws an exception, which I don't want it to do. I want it to loop the else statement until the input is an integer.
I tried embedding a while loop within the else statement but it started getting messy and I couldn't figure out how to work it. Any help would be appreciated.
import java.util.*;
import java.util.concurrent.TimeUnit;
public class NumbersArray
{
int[] numbers = new int[5]; // Defines new array string with length of 5 characters
Scanner sc = new Scanner(System.in);
int length = numbers.length; // Defines length int, calculates how many in numbers int
public void inputToNumbers()
{
for(int i=0; i<length; i++) // Declares i as 0, while i less than length loop runs. Increments each time
{
System.out.println("Input five whole numbers, separated by new lines:" + " (" + (i+1) + "/5)");
String inputtedNums; // Declares inputtedNums string
inputtedNums = sc.nextLine(); // Inserts input
if (inputtedNums.matches("[0-9]+")) // Checks if the input is numbers only
{
numbers[i] = Integer.parseInt(inputtedNums); // Parses string input into integer numbers
}
else
{
System.out.println("Error! You inputted an invalid number, try again." + " (" + (i+1) + "/5)");
inputtedNums = sc.nextLine(); // Takes user input
numbers[i] = Integer.parseInt(inputtedNums); // Parses string input into integer numberS
}
}
}
public void printTheNumbers()
{
for(int x=0; x<length; x++)
{
System.out.println(numbers[x]);
}
}
public static void main(String[] args)
{
NumbersArray na = new NumbersArray();
na.inputToNumbers();
na.printTheNumbers();
}
}