【问题标题】:Why cant I simply check if a variable is null instead of checking for different exceptions?为什么我不能简单地检查变量是否为空而不是检查不同的异常?
【发布时间】:2016-06-29 21:05:53
【问题描述】:

考虑一下,如果userChoice 不是整数:

Scanner choice = new Scanner(System.in);
int userChoice = choice.nextInt();
if(....){
    .... //not important
}
else if(userChoice == null){
    System.out.println("wrong input..");
    System.exit(0);
}

为什么我不能这样做?而是必须这样做:

import java.util.InputMismatchException;

..... //bunch of code

Scanner choice = new Scanner(System.in);
    int userChoice;
    try {
        userChoise = choice.nextInt();
        if(...){
          ..... //not important
        }
    }
    catch(InputMismatchException e) {
        System.out.println("wrong input..");
        System.exit(0);
    }

我认为如果我输入 char 而它期望 int 它只会返回 null。因此,如果我检查 null 那么就足够了。那么我错过了什么/没有理解什么?

所以这不是关于 Scanner 库的问题。如果你想把它归结为我不知道整数不能是null。所以认为这是重复的用户,它可能是。但这肯定不是您建议的帖子的重复..

【问题讨论】:

标签: java


【解决方案1】:

int 不能为空。它可以是其范围内的任何数字。

【讨论】:

  • 请更准确一点:int 不能为空; Integer 可以; integer 在 Java 中不是一个东西。
  • 我确实说整数不是Integer,int 是整数的缩写。
  • @FelixRosén 显然是;但是通过说“整数”,不清楚您是指Integer(可以为空)还是int(不能为空)。
  • @FelixRosén 是的。 Integer 通常指的是java.lang.Integerinteger 不是 Java 中的标准类型。
【解决方案2】:

如果要返回 null,除了需要使用 Integer 而不是 int 之外,不建议这样做。主要原因是检查输出是否为空很容易被遗忘,并可能在程序的后期导致错误情况。

但是,必须捕获异常,否则它会爬上堆栈。异常可以更容易地找出错误发生的位置(如果它们有正确的内容,它们还会说明为什么会发生)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 2012-02-05
    相关资源
    最近更新 更多