0

I have following java code, which accepts 10 string input. i need to accept only the unique input . By this i mean to say that if 1st device address is "123" and 2nd device address is also "123" then it should display an error.

This is the sample code and i have shorten it.

  InputStreamReader istream = new InputStreamReader(System.in) ;
  BufferedReader bufRead = new BufferedReader(istream) ;

  for (int i=0; i<10; i++)
  {
  try {
    System.out.println("Device Address: ");
    String DevAdd = bufRead.readLine();

    System.out.println("Device address:" + DevAdd);
     }
     catch (IOException err) {
          System.out.println("Error reading line");
     }
     catch(NumberFormatException err) {
          System.out.println("Error Converting Number");
     }     
     }
1
  • Why don't you use HashMap<String>? Read value, check if it's in a map, if it's - throw an exception; if not - add to map Commented Jan 10, 2014 at 6:34

6 Answers 6

2

Use a Set<String>, like this:

// before the loop:
Set<String> set = new HashSet<String();

// inside loop:
String id = // read id;

if (!set.add(id)) {
    // error - id has been used before
}

The add() method of Set returns true if the set was changed by the operation, which will be false if the value has been seen before, because Sets don't allow duplicate values and attempting to add a value already in the Set will be a no-op.

If the value has not been seen before it is added to the Set, which is what you want ready for the next iteration.

Sign up to request clarification or add additional context in comments.

Comments

1

Check this out:

Set<String> inputSet= new HashSet<String>();

for (int i = 0; i < 10; i++) {
    try {
        System.out.println("Device Address: ");
        String DevAdd = bufRead.readLine();

        // Check if already exists. If yes, throw exception
        if(inputSet.contains(DevAdd)) {
            throw new Exception("Already exists");
        }
        //  Indicates input does not exist in the set. Add it       
        inputSet.add(DevAdd);

        System.out.println("Device address:" + DevAdd);
    } catch (IOException err) {
        System.out.println("Error reading line");
    } catch (NumberFormatException err) {
        System.out.println("Error Converting Number");
    }
}

Comments

0

Hold those values in a Map as Map<device,address> so that when ever you try validate the address is unique or not just access these map and you can easily know whether the address is unique or not

Comments

0

store it in a collection check if the value exists and throw error ..
The same can be done using Set, but even if you don't check (req to throw an exception) if the value exists it will only allow unique value to be added .. the following two thing can be done

1) Use something like if (!set.add(input)) as mentioned by Bohemian
2) Use set.contains

4 Comments

Show an example. Also, a set will be better (map.containsKey() rather than containsValue())?
Yes, but Set won't throw an exception if you give it a duplicate value. But it does return a boolean that can be checked
you can do a set.contains to check if the value exists
yes, updated my answer, Set would definitely be a better alternative
0

Though set is the best suited datastructure for this senario as it does not allow duplicates,(See ankur answer for set ) you can also use lists like below.

public class HelloWorld{

     public static void main(String []args){
        InputStreamReader istream = new InputStreamReader(System.in) ;
  BufferedReader bufRead = new BufferedReader(istream) ;
  List<String> list=new ArrayList<String>();
  for (int i=0; i<10; i++)
  {
  try {
    System.out.println("Device Address: ");
    String DevAdd = bufRead.readLine();
    if(!list.contains(DevAdd))
    list.add(DevAdd);
    else
    throw new Exception("Already exists");
    System.out.println("Device address:" + DevAdd);
     }
     catch (IOException err) {
          System.out.println("Error reading line");
     }
     catch(NumberFormatException err) {
          System.out.println("Error Converting Number");
     }     
     }
     }
}

Comments

-1

Better store it in a Set. Every time you before you add an entry to the set check if it belongs to the Set. If no add it else throw error.

3 Comments

You can see example in ankurs answer.
Then what's the use of yours?
He posted the answer after me.

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.