Search code examples
javaarraysloopswhile-loopprimitive

JAVA - Storing Int & Float in array but not other data type


I'm a beginner at JAVA.

I'm writing a program that has a menu and gives the user the ability to select options such as the size of the array, the elements in the array and more. So I've all of it working and I'm finalizing the boundaries to loop back in the event a different data element is inputted by the user.

My question - How can I create a loop that will store ints & floats but loopback if another primitive is selected?

int a;

for (int i = 0; i<array.length;i++) {
    boolean validate = false;
    System.out.print("Give me a value");
    while (validate == false) {
        a = input.nextInt();
        if (input.hasNextFloat()) {
            numbers[i] = input.nextFloat();
            validate = true;
        }
        else if (input.hasNextInt()) {
            a = input.nextInt();
            numbers[i] = 1.0f *a;
            validate = true;
        }
        else {
            System.out.println("This is not an acceptable primitive. Try again");
            validate = false;
        }
    }
}

Solution

  • The first thing is about your specification of looping back if you get a primitive type.

        if (input.hasNextFloat()) {
            // Catches float
        } else if (input.hasNextInt()) {
            // Catches int
        } else {
            // Catches any other type
        }
    

    While the first condition catches float and the second condition catches int, the else will catch any other type. While this may be any of the remaining 6 primitive types, it may also be a String (which is a reference type, not primitive.

    The second thing is that an int is a valid float, but a float is not a valid int; That is, if you are scanning for a float and receive an int as input, you will accept it as a float. As you are converting the int to a float anyway, checking for an int is redundant as it will never succeed if it fails validation as a float.

    Likewise with respect to primitives, all floats are doubles, all shorts are ints, some longs are ints, etc. So your distinction of "loop back if another primitive type is selected" is a little iffy.

    Another thing is you try to read an int at the beginning of the for loop - This will throw a InputMismatchException exception if the input is not an int. This may have been done to consume the line, but it simply skips a value best case scenario (throwing an Exception being worst). Instead, you should consume the line if the value is determine not to be of an appropriate format to avoid getting stuck in an infinite loop.

    else {
        System.out.println(input.next() + " is not an acceptable primitive. Try again");
    }
    

    The validate boolean is only used to essentially not skip an index. Consider just decrementing the iterative counter in the for loop to avoid the additional if-statement as the for loop will increase it again. Though this will reprint the "Give me a value" message, so this comes down to preference.

    else {
        System.out.println("...");
        i--;
    }
    

    Something like this will achieve what you want:

    float[] array = new float[3];
    Scanner input = new Scanner(System.in);
    for (int i = 0; i<array.length;i++) {
        System.out.print("Give me a value: ");
        if (input.hasNextFloat()) {
            array[i] = input.nextFloat();
        } else {
            System.out.print(input.next() + " is not an acceptable type. ");
            i--;
        }
    }
    

    Another thing to note is you don't need to convert the int to a float unless this is explicitly what you want to do. The wrapper types for int and float both extend Number, so you could, instead, have a Number array.

       Number array[] = new Number[size];
       ...
       array[0] = 10;
       array[1] = 1.5f;