java: HashSet to show error message on inputing duplicate Integer values

1.1k Views Asked by At

I have to write a program which allows the user to enter 10 integers and displays an error message each time the user enters an integer which was previously input using a HashSet. So far, I have come up with this but the problem is that the error message appears each time I input a number.

package lesson1;
import java.util.*;

public class MyClass1{

public static void main(String[] args) {

    Set<Integer> h= new HashSet<Integer>();

    Scanner input= new Scanner(System.in);

    for(int i=0; i<10;i++){

        Object s=h.add(input.nextInt());

        if(s!=null){

            System.out.println("Duplicates are not allowed");
        }

    }


    System.out.println(h);


      }

}
3

There are 3 best solutions below

0
On BEST ANSWER

Set.add returns true if the element exists, otherwise false. You are checking the result for null. You need to change your code to:

    boolean nonDuplicate = h.add(input.nextInt());
    if(!nonDuplicate) {
       System.out.println("Duplicates are not allowed");
       // ...
0
On

Actually friend your below condition is wrong

 Object s=h.add(input.nextInt());

    if(s!=null){

                System.out.println("Duplicates are not allowed");
            }

you have to replace it with

boolean s=h.add(input.nextInt());

        if(!s){

                System.out.println("Duplicates are not allowed");
            }
0
On
import java.io.*;
import java.util.*;
import java.lang.*;

public class mainactivity {
public static void main(String a[]) {
    Set<Integer> h = new HashSet<Integer>();

    Scanner input = new Scanner(System.in);

    for (int i = 0; i < 3; i++) {

        boolean check = h.add(input.nextInt());

        if (!check) {

            System.out.println("already exist");
        }
    }
    System.out.println(h);

}
}

here is the working code