Ilia Hoss Ilia Hoss - 12 days ago 8
Java Question

How can I use a method to check if the new element that I want to add to my array hasn't already been added?

Im working on a school project and I am suppose to create a program that will display a 2 x 2 grid of numbers (randomly generated from 1 - 16). This program will then sort it out step by step.

I am supposed to have a logic check class.

I'm trying to make a method where it will take the value that the main() program wants to add, check to see if its already in the array or not, and return false if that number is already there or true if not.

class LogicStatementsV2 {
//Declare constants
private final int LENGTH_OF_INDEX = 16;
//Create an array of how the index of the array should look like
int[] finalIndex = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
//Creates an array of length 16 which will be filled as the main program uses a random number generator.
int[] buildIndex = new int[LENGTH_OF_INDEX];

/**Method that is called to add a random number if that number hasnt been entered
* @param n The integer that the main class will generate from a random number generator
* @return wether that number is already in the array or not
*/
public boolean addIfValid(int n) {
for (int i = 0; i < 16; i++) {
if (n == buildIndex[i]) return false;
else return true;
}
}
}


For some reason the first to last } keeps saying that a return value is required.

What am I doing wrong?

Answer

The else return true; doesn't belong in the loop. Only once you've looped through all the elements and found no duplicates can you safely return true:

public boolean addIfValid(int n) {
    for (int i = 0; i < 16; i++) {
        if (n == buildIndex[i]) return false;
    }
    return true;
}