[英]Converting split strings into int and adding them
我有一個相當愚蠢的問題,但我找不到任何修復方法。 我有一個掃描儀設置,可以打印出適當格式的線條。 這是我在該程序中的while循環:
while (fileScan.hasNextLine()){
String line = null;
line = fileScan.nextLine();
String[] element = line.split (":");
if(line.matches("\\w+\\s?\\w+?\\s?\\w+?\\s[:]\\s\\w+\\s?\\w+?\\s?\\w+?\\s[:]\\s\\d+\\s[:]\\s\\d+")){
count++;
System.out.println(element[0]+"["+element[2]+"]\t"+"|"+element[1]+"["+element[3]+" ]");
} else {
invalidLines++;
System.out.println("Line declined.");
}
}
我需要做什么才能繼續添加元素[2]的所有值(假設它們都是字符串,我確實知道將它們轉換為int是必要的)並在末尾打印一行總和為添加元素[2]的。
如果你只是簡單地指出我正確的方向,我將非常感激。
您可以在開始掃描文件之前添加sum字段,然后當發生行匹配時,執行sum += Integer.parseInt(element[2]);
掃描完成后,打印sum的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.