Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tell user if number entered is already stored inside the array

Tags:

java

I have this code that asks the users to enter an array size (must not exceed 50) and the array size is successfully set to the array.

My problem is in the second piece of code. Basically, I want it to store the numbers entered by the user (which works) BUT, if the number was already given to the array, the user is told that that number has already been added and the number is not stored. Example: User enter 1, 4, 6, 1. When 1 is given again the program should tell the user that the number 1 has already been stored in the array.

What can I do to make the program (with arraylists I could use .contains , but arrays dont have this it seems)

public static void main(String[] args) {

    Scanner reader = new Scanner (System.in);

    int[] listA;

    while (true) {

        System.out.println("Enter array size for listA: ");
        int listAsize = Integer.parseInt(reader.nextLine());

        if (listAsize > 50) {

            System.out.println("Array size must not exceed 50!");

        } else { 

            listA = new int [listAsize];
            //System.out.println(listA.length);
            break;
        }

    }


    int counter = 0;

    while (counter < listA.length) {

        System.out.print("Enter number to add to listA: ");
        int inputListA = Integer.parseInt(reader.nextLine());

        **if (listA.equals(listA[counter])) {**

            System.out.println(inputListA + " was already added to the array, enter a different number");

        } else {


            listA[counter] = inputListA;
            counter++;

        }
    }
like image 215
user3116280 Avatar asked Jan 11 '23 15:01

user3116280


2 Answers

This condition is incorrect:

listA.equals(listA[counter])

you need to set up a loop that goes from zero to counter-1, inclusive, and checks each element against the inputListA value. If a value is there, the loop should set a boolean flag, like this:

boolean dup = false;
for (int i = 0 ; i != counter ; i++) {
    if (listA[i] == inputListA) {
        dup = true;
        break;
    }
}
// If we went through listA up to count and dup remained false,
// listA must be a new number; otherwise, it's a duplicate.
if (dup) {
    System.out.println(inputListA + " was already added to the array, enter a different number");
}
like image 159
Sergey Kalinichenko Avatar answered Feb 02 '23 20:02

Sergey Kalinichenko


Problem in your code:

if (listA.equals(listA[counter]))

This is not going to be true for int listA[]

Use a HashSet<Integer> instead

  • no need to specify initial size
  • add() will return false if element is already present
like image 25
jmj Avatar answered Feb 02 '23 19:02

jmj