Scanner Class InputMismatchException and Warnings

江枫思渺然 提交于 2019-12-25 03:47:25

问题


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));
        }
    }
}

回答1:


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));
        }
    }
}


来源:https://stackoverflow.com/questions/25877199/scanner-class-inputmismatchexception-and-warnings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!