首页 > 解决方案 > 尝试使用 parseInt() 和 trim() 时出现 NumberFormatException 无法修复它

问题描述

嗨,我正在尝试解决 CodeWars 中的一个 Kata(编码练习练习),它被称为“Your order, please”(我的代码很有可能无法解决它,但我真的只是想摆脱错误..最后有一个练习链接,以防你想查看)

无论哪种方式,Kata 基本上说的是,您将获得一个字符串,例如

"4of Fo1r pe6ople g3ood th5e the2" 

你必须通过获取 int 并以正确的顺序返回来对单词进行排序,所以

"Fo1r the2 g3ood 4of th5e pe6ople"

现在我编码的内容应该遍历每个元素并获取数字然后对其进行排序,所以我尝试使用 parseInt 但它不起作用。我在另一篇文章中读到 trim() 会摆脱...

java.lang.NumberFormatException: For input string: "4of" //trim did not fix it

我不确定我是否没有正确实现 trim() 或 parseInt() 或有什么问题,非常感谢您提供任何帮助,并感谢您抽出宝贵时间阅读本文。事不宜迟,这里是代码。

public class Kata {
public static String order(String words) {
    String[] unordered = words.split(" ");
    String[] order = new String[unordered.length];
    System.out.println(unordered.length);
    
    for(int i = 0; i < unordered.length; i++){
        int correctIndex = (Integer.parseInt(unordered[i].trim())) -1;
        order[correctIndex] = unordered[i];
        System.out.println(unordered[i]);
    }
    
    return "I will return order concatenated";
  }

  public static void main(String[] args) {
      System.out.println(order("4of Fo1r pe6ople g3ood th5e the2"));
  }

}

和错误......(6是它之前的输出)

6
Exception in thread "main" java.lang.NumberFormatException: For input string: "4of"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at Kata.order(Kata.java:8)
    at Kata.main(Kata.java:17)

https://www.codewars.com/kata/55c45be3b2079eccff00010f/train/java (Kata 的链接)

标签: javaerror-handlingnumberformatexception

解决方案


只需删除所有非数字字符(通过使用正则表达式替换),然后将结果值解析为整数。

for (int i = 0; i < unordered.length; i++){
    String wordNum = unordered[i].trim().replaceAll("\\D+", "");
    int correctIndex = (Integer.parseInt(wordNum)) - 1;
    order[correctIndex] = unordered[i];
}

推荐阅读