-1

I want to change the string input to character but when I run the code error occurs "Exception in thread "main" java.lang.NumberFormatException: For input string: "" ".

    Map<Integer, Character> c = new HashMap<Integer, Character>();
    Scanner sa = new Scanner(System.in);
    for (int i = 0; i <3 ; i++) {
        System.out.println("Enter key");
       Integer a = sa.nextInt();
        System.out.println("Enter value");
        char d = (char) Integer.parseInt(sa.nextLine());
        c.put(a,d);
    }
    System.out.println(c);
Einstein
  • 13
  • 3
  • Use `sa.nextLine()` before reading the value. See: [Issues with nextLine()](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Pavel Smirnov Jul 22 '19 at 08:50
  • You should be avoiding the use of the legacy `char` as it is limited to a subset of the Unicode characters (the “basic plane”). Focus instead on using the code point numbers. – Basil Bourque Jul 22 '19 at 09:07

1 Answers1

0

I have modified your code, This will work for you please make sure that you should enter only one char while giving input, if you are giving string more than one chars then it will take first char only.

Map<Integer, Character> c = new HashMap<Integer, Character>();
    Scanner sa = new Scanner(System.in);
    for (int i = 0; i <1 ; i++) {
        System.out.println("Enter key");
       Integer a = sa.nextInt();
        System.out.println("Enter value");
        //added new code 
        String str = sa.next();
        char d = str.charAt(0);
        c.put(a,d);
    }
    System.out.println(c);
  • it worked :). But what will be the solution in more then one input. – Einstein Jul 22 '19 at 09:02
  • @Einstein What do you mean by saying "more than one input"? Give an example. – Elyas Hadizadeh Jul 22 '19 at 09:04
  • @ElyasHadizadeh like if I run the loop for 2 times it gives an error. – Einstein Jul 22 '19 at 10:23
  • @Einstein Are you sure? I tested the above-mentioned code for various time, it works. What type of error do you get and what are your inputs? – Elyas Hadizadeh Jul 22 '19 at 10:28
  • @ElyasHadizadeh if i input a same key for the two inputs. In output it gives only the last value and if i input different keys it output both values . can u tell why?. – Einstein Jul 22 '19 at 10:51
  • @Einstein Well, honestly it is another question. Anyway, It is the nature of HashMap because it tends to have one key and one value. If you would like to have One-Key and Multiple-Value check this question: https://stackoverflow.com/a/8229518/3881354 – Elyas Hadizadeh Jul 22 '19 at 11:00