扫描仪类InputMismatchException和警告 [英] Scanner Class InputMismatchException and Warnings
问题描述
我在运行该程序时遇到麻烦.该程序采用诸如"A = 7"之类的表达式,并将变量A(字符串)和数字7放入Map容器中.如果不是我正确解析了导致错误或其他原因的字符串,我就不是.
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.
代码
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));
}
}
}
推荐答案
,您将获得Commander.java使用未经检查或不安全的操作.因为您在HashMap之后缺少<>.
you get Commander.java uses unchecked or unsafe operations. because you are missing <> after HashMap.
Map<String,Integer> expression = new HashMap<>();
如果下一个标记与有效的Integer正则表达式不匹配或超出范围,则sc.nextInt()可能导致
和InputMismatchException.这是更新的代码.
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));
}
}
}
这篇关于扫描仪类InputMismatchException和警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!