0

I am having trouble running this program. The program takes an expression such as "A = 7" and puts the variable A (String) and the number 7 in a Map container. I'm not if i'm not parsing the string correctly which is causing the error or for some other reason.

    Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:909)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at Commander.main(Commander.java:21)

Furthermore, I get the following warning message which is actually a first

Note: Commander.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

The CODE

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

public class Commander
{
    public static void main(String[] args)
    {
        Map<String,Integer> expression = new HashMap();

        Scanner sc = new Scanner(System.in);

        String Variable , assignmentOperator;
        int Value;

        while(sc.hasNextLine())
       {

            Variable = sc.nextLine();
            assignmentOperator = sc.nextLine();
            Value = Integer.parseInt(sc.nextInt());

            expression.put(Variable,Value);

            for(String key: expression.keySet())
                System.out.println(key + " - " + expression.get(key));
        }
    }
}
Mutating Algorithm
  • 2,604
  • 2
  • 29
  • 66

1 Answers1

0

you get Commander.java uses unchecked or unsafe operations. because you are missing <> after HashMap.

Map<String,Integer> expression = new HashMap<>();

and InputMismatchException can be caused by sc.nextInt() if the next token doesn't match the valid Integer regex or is out of range. Here is updated code.

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

public class Commander
{
    public static void main(String[] args)
    {
        Map<String,Integer> expression = new HashMap<>();

        Scanner sc = new Scanner(System.in);

        String Variable , assignmentOperator;
        int Value;

        while(sc.hasNextLine())
       {

            Variable = sc.nextLine();
            assignmentOperator = sc.nextLine();
            Value = Integer.parseInt(String.valueOf(sc.nextInt()));

            expression.put(Variable,Value);

            for(String key: expression.keySet())
                System.out.println(key + " - " + expression.get(key));
        }
    }
}
sol4me
  • 15,233
  • 5
  • 34
  • 34