0

How am I going to identify the duplicated inputted integer like If I input 1 1 2 3 4, it will say number 1 is been duplicated

import java.util.*;

public class Haha {

    static Scanner console = new Scanner(System.in);

    public static void main(String[] args) {

        int[] items = new int[5];
        int sum;

        System.out.println("Enter five integers: ");
        sum = 0;

        for (int counter = 0; counter < items.length; counter++) {
            items[counter] = console.nextInt();
            sum = sum + items[counter];
        }

        System.out.println("The sum of the numbers = " + sum);
        System.out.print("The numbers in the reverse" + "order are: ");

        for (int counter = items.length - 1; counter >= 0; counter--) {
            System.out.print(items[counter] + " ");
        }

        System.out.println();
    }
}
3
  • How will you do it yourself on a piece of paper? Commented Dec 12, 2014 at 7:19
  • Use a hashMap to store the inputted values, so you can see in the hashMap if the value is already entert. Commented Dec 12, 2014 at 7:20
  • @Tiny haha was really original (and useless) you should have convert it to Haha instead! Commented Dec 12, 2014 at 7:20

1 Answer 1

5

All you need is a Set :)

    int[] arr = { 1, 1, 2, 3, 4,3 };
    Set<Integer> hs = new HashSet<Integer>();
    for (int i = 0; i < arr.length; i++) {
        boolean b = hs.add(arr[i]);  // add returns false if the value is already present in the set
        if (!b) {
            System.out.println("duplicate value is : " + arr[i]);
        }
    }

O/P :

duplicate value is : 1
duplicate value is : 3
Sign up to request clarification or add additional context in comments.

1 Comment

TheLostMind is correct. Instead using int array use power of collection framework which will let you more control over values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.