2014-12-05 160 views
-2

輸入文件以這種方式每次有一行數據:第1行:字符串,第2-4行:整數,第5行:字符串等我需要計數字符串的總數並忽略整數。我怎麼能這樣做?這裏是我的代碼:計算.txt輸入文件中的字符串出現次數

import java.util.Scanner; 
import java.io.*; 
public class Project5 { 

public static void main(String[] args) { 
    Scanner in = new Scanner(System.in); 
    System.out.println("Enter the file name: "); 
    String fileName = in.nextLine(); 
    int stringCounter = 0; 
    try { 
     File file = new File(fileName); 
     Scanner inputFile = new Scanner(file); 
     String SnumStudents = inputFile.nextLine(); 
     int numStudents = Integer.parseInt(SnumStudents); 
     Student [] studentList = new Student[numStudents]; 
     for (int i = 0; i < numStudents; i++) 
     { 
      String line = inputFile.nextLine(); 
      String score1 = inputFile.nextLine(); 
      String score2 = inputFile.nextLine(); 
      String score3 = inputFile.nextLine(); 
      studentList [i] = new Student(line, Integer.parseInt(score1), Integer.parseInt(score2), Integer.parseInt(score3)); 
     } 
     System.out.println("Name\t\tScore1\tScore2\tScore3\tTotal"); 
     System.out.println("---------------------------------------------"); 
     for (int i=0; i< studentList.length;i++){ 
      System.out.println(studentList[i].getName() + "\t" + studentList[i].getScore1() + "\t" + studentList[i].getScore2() + "\t" + studentList[i].getScore3() + "\t" + studentList[i].getTotal()); 
     } 
     System.out.println("---------------------------------------------"); 
     Integer i = Integer.valueOf(SnumStudents); 
     stringCounter++; 
     System.out.println(stringCounter); 
     inputFile.close(); 
    } catch (IOException e) { 
     System.out.println("There was a problem reading from " + fileName); 
    } 
    finally { 
    } 
    in.close(); 
} 
} 

輸入文件:

9 
Andy Borders 
200 
250 
400 
John Smith 
120 
220 
330 
Alvin Smith 
225 
300 
278 
+0

請參閱正則表達式(正則表達式) – NickJ 2014-12-05 15:46:55

+0

我們還沒有教過關於使用它。我需要一種本質上是初學java的方法。 – 2014-12-05 15:49:51

+0

我無法弄清楚如何讓它只添加字符串而不是整數。 – 2014-12-05 15:50:50

回答

0

一個可行的辦法(僞代碼)

  1. 初始化計數器(跟蹤弦數)

    int stringCounter = 0; 
    
  2. 使用Reader or a Scanner

    Scanner scan = new Scanner(file); 
    
  3. 遍歷每一行,並確定是否行是一個數字,試圖一旦退出循環解析值

    while(scan.hasNext()) { 
        String currentLine = scan.nextLine(); 
        try { 
         Integer i = Integer.valueOf(currentLine); 
        } catch (NumberFormatException nfe) { 
         stringCounter++; 
        } 
    } 
    
  4. 您的計數器將有答案

+0

我用我的嘗試更新了它。我無法獲得兩個nameTotal變量鏈接。 – 2014-12-05 16:36:38

+0

請提供一個文本文件的例子....你是讀實際的數字還是單詞「int」? – gtgaxiola 2014-12-05 16:43:21

+0

添加了輸入文件。 – 2014-12-05 16:45:35

相關問題