2013-12-20 30 views
0

我試圖編寫一個程序,逐行掃描文本文件並在每行上添加一些整數。有問題的文本文件的格式如下:使用循環和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); 
} 
+4

那麼有什麼不按預期工作? – Eran

+0

該方法似乎更復雜,它需要,我會利用文件中每行的循環中的String類的split和equals方法。 –

+0

當我打印「policyCount」和「itemAmount」時收到的值爲0,這是錯誤的。對不起,我應該在原文中澄清。 – user3120540

回答

0

這似乎工作:

import java.io.File; 
import java.io.IOException; 
import java.util.Scanner; 

public class Main 
{ 
    public static void main(String[] args) throws IOException 
    { 
     String filename = "policy.txt"; 
     Scanner input = null; 
     double itemAmount = 0; 
     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 (policyType == 'A' || policyType == 'M') 
      { 
       policyCount++; 
       itemAmount += Character.getNumericValue((clean.charAt(24))); 
      } 
     } 
     input.close(); 
     System.out.println(policyCount); 
     System.out.println(itemAmount);    
    } 
} 

請注意,這隻會在24列的個位數的工作。如果它可能包含更多數字,則必須在乾淨的情況下執行子字符串,然後使用Double.valueOf()。

+0

這正是我所期待的。感謝您的幫助,非常感謝! – user3120540

0

我想會希望把

itemAmount = itemAmount + input.nextInt(); 

if (policyType == 'A' || policyType == 'M'){ 

} 

希望這有助於。

此外,你還沒有使用'讀'字符串。你似乎在跳過線條。
使用read.split(「」)來獲取令牌數組。
然後使用第三個標記解析爲整數。
如果條件爲真,則添加它。