2013-10-24 45 views
0

我在Java中使用BlueJ,我對它很陌生。如果有一件事我不擅長Java,那就是數組,更不用說二維數組了。希望有人能夠幫助我參與這個項目,因爲我覺得有點不知所措,我不確定哪裏可以開始。二維數組問題。希望尋求幫助

此程序的目的是使用一個二維來統計一個.TXT文件的政治民意調查結果。 輸入文件「PROG4IN.TXT」包含每個選民輪詢的一行。每行包含受歡迎的候選人的姓名和選民的年齡。 使用有兩行三列的數組,我必須按照青睞的候選人和年齡組合計算選民;三個年齡組分別是18-29,30-49和50-99。

這是所期望的最終輸出應該是這樣的:

Candidate 18-29 30-49 50-99 Total 
Krook   2  4  6  12 
Leyer   3  3  2  8 

以供參考,這是在「PROG4IN.TXT」文件:

Krook 45 
Leyer 40 
Krook 76 
Leyer 55 
Krook 20 
Krook 50 
Leyer 28 
Krook 30 
Leyer 23 
Krook 72 
Krook 42 
Krook 81 
Leyer 64 
Krook 52 
Leyer 18 
Leyer 34 
Krook 60 
Krook 26 
Leyer 49 
Krook 37 

我必須使用這個模板:

public class Table { 
    private int[][] table; 
    private String[] names; 

    public Table() { 
     // Create the two-dimensional tally array "table" 
     // having 2 rows and 3 columns. Row 0 corresponds 
     // to candidate Krook and row 1 to candidate Leyer. 
     // The columns correspond to the three age groups 
     // 18-29, 30-49, and 50-99. Initialize all the 
     // tallies to zero. Create the array "names" to 
     // hold the candidate names: names[0]="Krook" and 
     // names[1]="Leyer". 
    } 

    public void tally(String name, int age) { 
     // Add one to the tally in the "table" array that 
     // corresponds to the name and age passed as arguments. 
     // Hint: Use the equals method to determine whether 
     // two strings are equal: name.equals("Krook") is 
     // true when name is "Krook". 
    } 

    public void report() { 
     // Use nested loops to print a report in the format 
     // shown above. Assume that the tallies have already 
     // been made. 
    } 
} 

畢竟,我必須創建一個創建Table對象的主類,來自PROG4IN.TXT的數據,並打印報告。

我希望有人能幫助我。

預先感謝您。

回答

0

你的陣列將是這樣的:

table = new int[2][3](); 

和裏面會是這樣:

{ 
{count for 1st age group for krook, for 2nd age group for krook, last group for krook} 
{count for 1st age group for leyer, for 2nd age group for leyer, last group for leyer} 
} 

所以,當你想添加到中年組leyer,例如,你會做表[1] [1] + =一些金額。

或者對於第三年齡組,krook,youd做了table [0] [2] + = someamount。