user3196742
user3196742

Reputation: 27

Array List from User Input with Validation

I am new to programming. I am attemping to create a ArrayList from user input. I need to validate that the user is not entering a negative number, prompt the users for correct input and continue accepting input. Once I have accepted all input, total of numbers entered. I can get the input and validation to work as long as the user does not type consective negative numbers. If the user types in consective negative numbers it no longer throws the validation error and the the negative number entered is subtracted from the total. I have tried rewriting this with do, if, while and everyway I can think of, but end of just making it worse. Thanks in advance for any help.

public static ArrayList<Double> readInputs()
{
ArrayList<Double> inputs = new ArrayList<>();
System.out.println("Please enter CU or Type q and Enter to Total.");          
Scanner in = new Scanner(System.in);
while (in.hasNextDouble())
{
double value = in.nextDouble();
if (value < 0)
{
System.out.println("Error: Can not be a Negative Value");
System.out.println("Please enter CU or Type q and Enter to Total.");
value = in.nextDouble();
}
inputs.add(value);
}
return inputs;
}  

Upvotes: 0

Views: 1453

Answers (2)

Sundeep
Sundeep

Reputation: 1606

Add a continue statement instead of reading the next value inside the if block

if (value < 0)
{
    System.out.println("Error: Can not be a Negative Value");
    System.out.println("Please enter CU or Type q and Enter to Total.");
    //value = in.nextDouble();
    continue;
}

This way, the validation happens for all inputs.

A continue statement will end the current iteration and the next iteration begins.

Upvotes: 2

user3192244
user3192244

Reputation: 86

Change if (value < 0) to while (value < 0)

Basically it will keep asking to enter if user input negative number.

    ArrayList<Double> inputs = new ArrayList<>();
    System.out.println("Please enter CU or Type q and Enter to Total.");
    Scanner in = new Scanner(System.in);
    while (in.hasNextDouble()) {
        double value = in.nextDouble();
        while (value < 0) {
            System.out.println("Error: Can not be a Negative Value");
            System.out.println("Please enter CU or Type q and Enter to Total.");
            value = in.nextDouble();
        }
        inputs.add(value);
    }
    return inputs;

Upvotes: 0

Related Questions