【问题标题】:Is there a way to ignore a string if it cannot be parseInt without try and catch?如果没有try and catch就无法解析字符串,有没有办法忽略它?
【发布时间】:2018-02-27 22:13:55
【问题描述】:

例如,如果我有一个显示不同整数的文本文件,但如果遇到一个包含字母的值,它将抛出 NumberFormatException。我已经多次看到会使用 try-catch 语句,但除此之外还有其他方法来处理此异常吗?这是一个名为“data”的txt文件的示例(注意三个整数之间用空格隔开)

545F6 6 100

12N45 A 50

下面的代码可以工作吗?

while (data.hasNextLine()){
    data.nextInt();
    if (!data.hasNextInt()){
        System.out.println("The number " + data.next() + " is invalid");
        data.next();
    }
}

我是 Java 的初学者,所以我很好奇是否有另一种方法可以忽略字符串,如果它不返回整数则表明它是无效的。

【问题讨论】:

  • 有点取决于“忽略字符串”的含义。如果你想忽略,说“545F6”,肯定有办法做到这一点。我相信nextInt() 会读到“545”,所以它不会立即对你有用。
  • 你想发生什么?从545F6 6 100 中读取545 或从中获取54576100
  • 这很复杂。细节决定成败。例如,0xcafebabe 可以被视为一个 int,而 0999 可以被拒绝,因为它不是一个正确的八进制数。您可以测试“[0-9]*”,但可选地,它可能有一个减号。它可能远远超过整数的值空间,或者仅仅超过 1。:) 更不用说像“MMXVIII”这样的罗马数字了

标签: java while-loop try-catch parseint


【解决方案1】:

您可能想尝试正则表达式并在简单的循环中使用它们,以检查在由空格字符分隔的给定字符串中是否只有数字存在(我在 cmets 中添加了更多解释):

    String a = "545F6 6 100";
    String b = "12N45 A 50";

    List<String> results = new ArrayList<>(); // here you will store matching numbers
    for(String str : a.split("\\s+")) { // for each String that you get after splitting source String at whitespace characters...
        if(str.matches("\\b[\\d]+\\b")) { //check if that String matches given pattern: word boundary-only digits-word boundary
            results.add(str); // it there is a match, add this String to results ArrayList
        } else {
            System.out.println("The number " + str + " is invalid");
        }
    }

    System.out.println("Valid numbers: " + Arrays.toString(results.toArray())); // just to print results
    results.clear();
    System.out.println();

    for(String str : b.split("\\s+")) {
        if(str.matches("\\b[\\d]+\\b")) {
            results.add(str);
        } else {
            System.out.println("The number " + str + " is invalid");
        }
    }
    System.out.println("Valid numbers: " + Arrays.toString(results.toArray()));

您从这些循环中获得的输出:

The number 545F6 is invalid
Valid numbers: [6, 100]

The number 12N45 is invalid
The number A is invalid
Valid numbers: [50]

您可能想在 Patternhere 类的 Java API 文档中阅读有关如何使用正则表达式的更多信息。

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多