【问题标题】:How to get the type of a variable [closed]如何获取变量的类型[关闭]
【发布时间】: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() 的目的是什么?

标签: java types gettype


【解决方案1】:

你似乎很困惑,

try {
  int score = input.nextInt();
} catch (InputMismatchException ime) {
  ime.printStackTrace();
}

根据Scanner#nextInt(),将始终为int 类型(否则您将获得异常)

将输入的下一个标记扫描为 int。

并注意 throws 说的是

InputMismatchException - 如果下一个标记与 Integer 正则表达式不匹配,或者超出范围

也可以先拨打Scanner#hasNextInt()

if (input.hasNextInt()) {
  int score = input.nextInt();
} else {
  System.out.println(input.next() + " isn't an int");
}

【讨论】:

    【解决方案2】:

    首先,正如他们在他们的 cmets 中已经提到的那样,您不需要这个。如果你的变量被定义为int int 并且你不必检查这个。

    其次,int 是一个原语,所以你不能说score.getClass()

    但是,在某些情况下(如果您编写一些必须关心几种但特定类型的通用代码),您可能希望将 if 语句修复如下:

    Integer score = .....
    .........
    if (Integer.class.equals(score.getClass())) {
       // your code here
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-03
      • 2016-12-03
      • 2015-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多