java - 尝试使用 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 的链接)
解决方案
只需删除所有非数字字符(通过使用正则表达式替换),然后将结果值解析为整数。
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];
}
推荐阅读
- c# - 最大化表单时如何调整表单内的对象大小以适应
- reactjs - 如何使用 React 构建大型表单
- python - 如何在不使用 pandas 更改文件中现有数据的情况下将新列附加到 Excel 文件?
- android - AppCompatDelegate#setDefaultNightMode() 从 API 23 的 SettingsActivity 返回后导致 MainActivity 冻结
- rust - 第二个可变借用错误,只有一个可变借用
- c++ - 选择blocking on available write fdset,直到进程被中断并更新
- discord.js - 如何为 Discord.js 中添加、删除和更改用户名的角色添加审核日志?
- typescript - TS 何时计算类型实例化(与错误相关:“类型实例化过深且可能无限”)?
- python - 如何将数据框列中的多个值拆分为单独的列
- c++ - 为什么结构声明违反 C++ 中的 ODR?