我試圖編寫一個程序,逐行掃描文本文件並在每行上添加一些整數。有問題的文本文件的格式如下:使用循環和if語句與掃描儀類
01-Jan-2012 ED521D 4 100 30 1499 M N Brewer
02-Jan-2012 ED925H 5 488 30 1499 A B Saini
02-Jan-2012 JF560D 3 275 40 949 M S Cooper
02-Jan-2012 ZK201U 1 359 40 474 R S Chadwick
我的目標是在第三列(4,5,3)加起來的數字,如果在倒數第二列中的字符是一個「M」或「一個」。所以程序應該使用上面的文本文件輸出12。這是我到目前爲止。
public static void main(String[] args) throws IOException {
String filename = "policy.txt";
Scanner input = null;
double itemAmount = 0;
String text = "";
int policyCount = 0;
input = new Scanner(new File(filename));
while (input.hasNext()) {
String read = input.nextLine();
String clean = read.replaceAll("\\P{Print}", "");
char policyType = clean.charAt(59);
if (input.hasNextInt()) {
itemAmount = itemAmount + input.nextInt();
input.nextLine();
if (policyType == 'A' || policyType == 'M'){
policyCount++;
}
}
else if(input.hasNext()){
text = input.next();
}
}
System.out.println(policyCount);
System.out.println(itemAmount);
}
那麼有什麼不按預期工作? – Eran
該方法似乎更復雜,它需要,我會利用文件中每行的循環中的String類的split和equals方法。 –
當我打印「policyCount」和「itemAmount」時收到的值爲0,這是錯誤的。對不起,我應該在原文中澄清。 – user3120540