0

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();
    }
}
josef
  • 73
  • 8
  • *I want it to loop the else statement until the input is an integer.* That is **not** possible, nor does it logically make any sense. Create a method to get the input. Don't return from the method until you have valid input. An infinite loop in that method, that only ends on valid input (for example). – Elliott Frisch Dec 07 '18 at 13:02
  • 2
    inside your else, you need to put your code in a while loop. i.e. while the input is not a valid integer, keep asking – Bentaye Dec 07 '18 at 13:03
  • @Bentaye thank you that worked perfectly! – josef Dec 07 '18 at 13:09
  • @josef you could also factor the input reading bit in a method that returns an int, and have the loop in that method to make the code easier to read. – Bentaye Dec 07 '18 at 13:10
  • @Bentaye I'm not sure what you mean by this? Can you give me an example? – josef Dec 07 '18 at 13:13
  • @Bentaye you should write your comment as an answrr, so it can be a reference for future askers. – Josef Ginerman Dec 07 '18 at 13:13
  • @josef I added an answer expanding on my comments – Bentaye Dec 07 '18 at 13:23
  • Possible duplicate of [Validating input using java.util.Scanner](https://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner) – Tom Dec 07 '18 at 13:42

3 Answers3

2

I think this will work fine.

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
            while (inputtedNums.matches("^-?[^\\d]+$")) // Checks if the input is not number 
            {
                System.out.println("Error! You inputted an invalid number, try again." + " (" + (i+1) + "/5)");
                inputtedNums = sc.nextLine();

            }
            numbers[i] = Integer.parseInt(inputtedNums);
            // Parses string input into integer numbers
        }
    }

My concern is that whether negative integers are allowed or not? I have included an optional negative number case. See working code here : https://ide.geeksforgeeks.org/fzy9sHCGtz

Regex Test : https://regex101.com/r/KKrpUu/1

Brij Raj Kishore
  • 1,465
  • 1
  • 9
  • 20
1

To expand on my comment, you can simplify your code this way:

Create an other method just to read a number from the console input and you can then call it again until you get an actual number. This replaces looping with recursion

public void inputToNumbers()
{
    int[] numbers = new int[5];
    for(int i=0; i<numbers.length; i++) {
        System.out.println("Input five whole numbers, separated by new lines:" + " (" + (i+1) + "/5)");
        numbers[i] = readNextnumber();
    }
}

private int readNextnumber() {
    Scanner sc = new Scanner(System.in);
    String inputtedNum = sc.nextLine();
    if(!inputtedNum.matches("[0-9]+")) {
        System.out.println("Error! You inputted an invalid number, try again.");
        return readNextnumber();
    } else {
        return Integer.parseInt(inputtedNum);
    }
}
Bentaye
  • 8,262
  • 4
  • 28
  • 36
0

Courtesy of @Bentaye, I added the following to my else statement:

        else
        {
            while(!inputtedNums.matches("[0-9]+"))
            {
                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        
        }

And this worked perfectly.

josef
  • 73
  • 8