2016-07-18 137 views
0

這個問題與我4天前製作的here有很大關係。
我需要做的是創造一個垂直直方圖其內容的學生的成績的occurencies(從1到10),它們在一個.txt文件中像這樣列出:垂直直方圖顯示不正確

馬克2
埃倫3
盧克7
埃倫9
JHON 5
馬克4
埃倫10
路1
JHON 1
JHON 7
埃倫5
馬克3
可7

這是我的代碼:

import java.util.Scanner; 
import java.io.*; 

public class GradeHistogram { 
    public static void main(String[] args) throws IOException { 
    Scanner fileScan = new Scanner(new File("RegistroVoti.txt")); 
    String line; 
    char currentChar; 
    int [] array = new int [10]; 
    int max = 0, currentValue; 

    while (fileScan.hasNext()) { 
     line = fileScan.nextLine(); 
     for(int j=0; j < line.length(); j++) { 

     currentChar = line.charAt(j); 

     if (currentChar == '1') 
      array[0]++; 
     else if (currentChar == '2') 
      array[1]++; 
     else if (currentChar == '3') 
      array[2]++; 
     else if (currentChar == '4') 
      array[3]++; 
     else if (currentChar == '5') 
      array[4]++; 
     else if (currentChar == '6') 
      array[5]++; 
     else if (currentChar == '7') 
      array[6]++; 
     else if (currentChar == '8') 
      array[7]++; 
     else if (currentChar == '9') 
      array[8]++; 
     else if (currentChar == '0') 
      array[9]++; 
     } 
    } 
    for(int i = 0; i <= 9; i++) { 
     if (array[i] > max) 
     max = array[i]; 
    } 
    currentValue = max; 
    for(int i = max; i > 0; i--) { 
     for(int j = 0; j < 10; j++) { 
     if(array[j] < i) 
      System.out.print(" "); 
     else 
      System.out.print("*"); 
     } 
     System.out.println(); 
    } 
    System.out.println("12345678910"); 
    } 
} 

然而,由於charAt()方法打印基於所述單個char星號他發現,它添加了數字「1」列中「10」的askerisks。

我真的試圖通過修改代碼nextInt()方法,但是當我跑了,被證明沒有星號...

我該如何解決這個問題?

任何反饋意見是讚賞!

預先感謝您!

回答

1

使用正則表達式從行中提取等級。使用該部分上的Integer.parseInt來獲取數字,而不是試圖自己實現解析:

Pattern pattern = Pattern.compile("^.+ (\\d+)$"); 

while (fileScan.hasNext()) { 
    line = fileScan.nextLine(); 
    Matcher m = pattern.matcher(line); 
    if (m.find()) { 
     array[Integer.parseInt(m.group(1))-1]++; 
    } 
}