【发布时间】:2014-08-27 13:07:13
【问题描述】:
我对 Java 很陌生,所以请原谅我的菜鸟问题。
如何使error checking 逻辑在语法上正确,我可以使用哪些内置方法?
public static void initialize(HighScores[] scores) {
Scanner input = new Scanner(System.in);
// capture input
for (int i = 0; i < 5; i++) {
System.out.println("Enter the name for score #" + i + ": ");
String name = input.next(); // Alex
System.out.println();
System.out.println("Enter the score for score #" + i + ": ");
int score = input.nextInt();
// Error checking
// if the 'input' is NOT of type 'int'
if (score.getClass().getSimpleName() != int) {
// Ask to input a numeric value
System.out.println("Please enter a numeric value! :)");
score = input.nextInt(); // inputting a value in again
}
System.out.println();
HighScores object = new HighScores(name, score);
scores[i] = object;
}
}
如果正确的话会是什么样子:
输入分数 #0 的名称: 亚历克斯
输入分数 #0 的分数: s
请输入一个数值! :) 5
输入分数 #0 的名称: 约翰
输入分数 #0 的分数: 3
....等等...
【问题讨论】:
-
如果你不输入
int,你会在这里得到一个错误:int score = input.nextInt(); -
你的问题被严重误导了。
-
根据这个问题,我猜你来自动态类型的背景......请记住,Java 是静态类型的。您不需要获取变量的类型,因为在您声明它时它已经存在。你写了
int score,所以你知道score必须是int。 -
@Anoop 这行不通,因为您不能在原始类型变量上调用方法。
-
@Anoop - 不需要反射。如果他必须使用反射来检查类型,
Scanner# nextInt()的目的是什么?