0

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;
}  
2
  • do you really think this line is gonna compile?? ArrayList<Double> inputs = new ArrayList<>(); Commented Jan 15, 2014 at 5:40
  • @SaurabhSharma of course it will... in Java 7. You should upgrade from your 8 year old version ;) Commented Jan 15, 2014 at 5:41

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.