-2

I have a function, which allow input key and value into Map.

here my code

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class MapDemo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Map<String, Integer> map = new HashMap<>();
        System.out.println("Elemment number: ");
        String sNum = input.nextLine();
        int iNum = Integer.parseInt(sNum);
        for (int i = 0; i < iNum; i++) {
            System.out.println("Key: ");
            String sKey = input.nextLine();
            System.out.println("Value: ");
            String sValue = input.nextLine();
            int iValue = Integer.parseInt(sValue);
            map.put(sKey, iValue);
        }
    }
}

I don't know how to check element next, which I will input. it the same with element before, and if it same I will input again.

2 Answers2

1

Add a while loop :

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    Map<String, Integer> map = new HashMap<>();
    System.out.println("Elemment number: ");
    String sNum = input.nextLine();
    int iNum = Integer.parseInt(sNum);
    for (int i = 0; i < iNum; i++) {
        String sKey ;
        do {
            System.out.println("Key: ");
            sKey = input.nextLine();
        } while (map.containsKey(sKey));

        System.out.println("Value: ");
        String sValue = input.nextLine();
        int iValue = Integer.parseInt(sValue);
        map.put(sKey, iValue);
    }
 }
Mustapha Belmokhtar
  • 1,231
  • 8
  • 21
-3

There is a Collection.contains() method available in every data structure that implements Collection interface !!!!

SPS
  • 183
  • 1
  • 2
  • 10