【问题标题】:Exeptions and parseInt豁免和 parseInt
【发布时间】:2020-01-03 15:59:09
【问题描述】:

为什么我的第一个方法“inputNumber”返回无限输出“这不是一个有效的数字” 而第二种方法返回问题“输入一个有效的数字:”

我不明白为什么带有 parseInt 的方法不做同样的事情...... 它们都抛出异常并都执行“catch”。

这是我的代码:

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.println("you typed the number: " + inputNumber(input));

}

public static int inputNumber(Scanner input) {
    int num = 0;
    while (num == 0) {
        System.out.print("Type a number: ");
        try {
            return input.nextInt();
        } catch (Exception e) {
            System.out.println("this is not a valid number");
        }
    }
    return num;
}

public int readNumber(Scanner input) {
    boolean running = true;
    while (running) {
        System.out.print("Write a number: ");

        try {
            int num = Integer.parseInt(input.nextLine());
            return num;
        } catch (Exception e) {
            System.out.println("this is not a valid number");
        }
    }
    return 0;
}
}

【问题讨论】:

  • 因为input.next() 不会消耗整行并使循环无限。 stackoverflow.com/questions/50672003/…
  • 提示:捕获所有类型的异常,然后打印一些硬编码的字符串......坏主意。打印异常本身,以了解真正出了什么问题!

标签: java exception try-catch parseint


【解决方案1】:
Please make few changes:
1. No need of num variable in inputNumber() method,
2. Make readNumber() method static.

你也可以试试这个 inputNumber() 方法的逻辑。

public static int inputNumber(Scanner input) {
   System.out.print("Type a number: ");
    try {
        return input.nextInt();
    } catch (Exception e) {
        System.out.println("this is not a valid number");
    }
    return 0;
}

【讨论】:

  • 非常感谢您检查我的代码和建议。但我并不是真的在我的代码中寻找编辑。我想知道为什么 parseInt 异常不同于任何其他异常,以及为什么它使得 while 循环不在无限循环中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-05
  • 2021-07-30
  • 2020-11-02
  • 2013-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多