How to validate scanner so only non negative doubles are added to array?

import java.util.Scanner;

public class ArrayReview {
public static void main(String[] args){
    double[] doublesArray = createArray();
    printArray(doublesArray);
}

//"input method" create array of 10 doubles
public static double[] createArray() {
    Scanner userInput = new Scanner(System.in);
    double[] array = new double[10];
    System.out.println("Input 10 non-negative double numbers");
    for(int i = 0 ; i < array.length ; i++) {
        //input validation
        while(!userInput.hasNextDouble()) {
            userInput.nextLine(); //throws away bad input
            System.out.println("Please input a valid double input");
        }
        if(userInput.hasNextDouble()) {
            array[i] = userInput.nextDouble();
        }
    }
    userInput.close();
    return array;
}

//print all values in an array of doubles
public static void printArray(double[] array) {
    for(int i = 0 ; i < array.length ; i++) {
        System.out.print(array[i] + " ");
    }
}
}

I need to validate all the users input so that only non negative numbers are allowed into the array. Currently I was able to check if the user inputs a letter or special character but negative numbers are still able to go into the array.

I’ve tried using the "<" operand in the while statement to see if the userInput<0 but i’m getting an error if i do that. Would I be better off making a method that is solely dedicated to checking if its a negative or not or is there an easier way?

>Solution :

You could extend the conditional expression of the while loop as follows:

for (int i = 0; i < array.length; i++) {
    double value;
    while (!userInput.hasNextDouble() || (value = userInput.nextDouble()) < 0) {
        userInput.nextLine(); // throws away bad input
        System.out.println("Please enter a valid, non-negative double value");
    }
    
    array[i] = value;
}

Leave a Reply