[英]why doesn't Integer.parseInt method work for splitted strings?
我正在嘗試使用 String split method 從具有特定格式的字符串中提取數字。 然后我想使用 Integer parseInt 方法將數字作為 int 類型獲取。 這是一個不起作用的示例代碼。 有人可以幫我嗎?
String g = "hi5hi6";
String[] l = new String[2];
l = g.split("hi");
for (String k : l) {
int p=Integer.parseInt(k);
System.out.println(p);
}
我收到此錯誤:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at com.company.Main.main(Main.java:36)
這里的問題很可能是String#split
給您的數組留下了一個或多個空元素。 只需過濾掉那些,它應該可以工作:
String g = "hi5hi6";
String[] parts = g.split("hi");
for (String part : parts) {
if (!part.isEmpty()) {
int p = Integer.parseInt(part);
System.out.println(p);
}
}
這打印:
5
6
這些是數組中的元素[, 5, 6]
你看到問題了嗎? 第一個元素是 Empty。
嘗試這個:
String[] l = new String[2];
l = g.split("hi");
for (String k : l) {
if (!k.isEmpty()) {
int p=Integer.parseInt(k);
System.out.println(p);
}
}
如果 Integer.ParseInt 沒有格式化,它總是會給你一個 Numberformat 異常。 它是一個 UnChecked Exception 所以程序員應該處理這個。
String g="hi5hi6";
String[] l=new String[2];
l=g.split("hi");
for(String k:l){
try
{
if (!part.isEmpty()) {
//the String to int conversion happens here
int p=Integer.parseInt(k.trim());
//print out the value after the conversion
System.out.println(p);
}
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.