[英]ArrayList String conversion to ArrayList Integer [on hold]
ArrayList<String> str = new ArrayList<String>();
ArrayList<Integer> results = new ArrayList<Integer>();
File file1 = new File("file3.txt");
try
{
Scanner s = new Scanner(file1);
s.useDelimiter("\\*-\\*");
str.add(s.next());
} catch (FileNotFoundException e)
{
System.out.println("File Not Found");
e.printStackTrace();
}
try
{
for (String num : str)
{
results.add(Integer.parseInt(num));
System.out.println(results);
}
} catch (NumberFormatException nfe)
{
System.out.println("Number Format is Not Correct");
nfe.printStackTrace();
}
str
是String
的ArrayList
和
results
是ArrayList
的Integer
我正在嘗試將String
的 ArrayList 轉換為ArrayList
的Integer
但得到NumberFormatException
。
在 String ArrayList
,我從序列文件中添加元素(數字作為字符串)。
我假設您擁有的是List<String>
並且您想將其轉換為List<Integer>
。 我想您已經可以從文件中讀取列表,因此我將跳過該部分。
public List<Integer> convertToIntegerList(List<String> inputs) {
if (inputs == null) {
return Collections.EMPTY_LIST;
}
List<Integer> converted = new LinkedList<>();
for (String input : inputs) {
try {
converted.add(Integer.parseInt(input));
} catch (NumberFormatException ex) {
// Note that Integer.parseInt() will throw a NumberFormatException
// if the argument doesn't represent a valid Integer.
// How you handle that is on you. For this one we are just going to ignore the invalid number and print it.
System.out.println("Failed to convert " + input);
continue;
}
}
return converted;
}
更新:根據更新后的問題,您的文件格式似乎不正確,並且您的inputs
包含無效值。 我將首先打印出列表的每個元素並確認它實際上是一個有效的輸入(文件讀取成功)
更新#2:
有幾件事看起來是錯誤的,但如果沒有示例文件,我無法真正說出究竟是什么,只能猜測。 因此,首先您要從正確的文件創建掃描儀。 請注意, Scanner.useDelimiter接受轉換為Pattern
的字符串作為正則表達式。 您給定的正則表達式\\*-\\*
表示您要使用的分隔符實際上是any character followed by a - and followed by any character
。
我相信你的文件看起來更像這樣
1-2-3-4...
用於該輸入的正確分隔符是scanner.useDelimiter("-");
這將拆分-
上的輸入並返回標記。 現在從您的代碼中,您只讀取一個令牌,第一個令牌,然后丟棄其他令牌。
我會將其轉換為
while (scanner.hasNext()) {
inputs.add(scanner.next());
}
同樣,所有這些都是猜測,添加輸入文件將消除混亂。
唯一可能的原因是這一行中的“num”不是表示有效數字的字符串:
results.add(Integer.parseInt(num));
在此行之前嘗試 System.out.println(num) 進行仔細檢查。 例如:
“123”這是可以解析為數字“123”的字符串,這不是。 你需要刪除前導字符
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.