2016-02-21 29 views
0

的分數時編譯該代碼僅示出最後一個輸入的分數當編譯該代碼僅示出最後一個輸入

import java.util.*; 
    public class TestII { 
    static Scanner key = new Scanner (System.in); 
    static int countNa = 0; 
    static int countSc = 0; 
    static int numSc; 
    static int numNa; 
    static int [] scores = null; 
    static String [] names = null; 
    public static void main(String[] args) { 
     System.out.println("How many name and scores"); 
     System.out.print("N> "); 
     numNa = key.nextInt(); 
     System.out.print("S> "); 
     numSc = key.nextInt(); 
     names = new String [numNa]; 
     scores = new int [numSc]; 
     readNameScores(); 
     showNamesScores(); 
    } 
    public static void readNameScores(){ 
     for (int i = 0; i < names.length; i++){ 
      countNa++; 
      System.out.print("Name "+countNa+": "); 
      names [i] = key.next(); 
      for (int j = 0; j < scores.length; j++){ 
       countSc++; 

        if (countSc > scores.length){ 
         countSc = 0; 
         countSc++; 
        } 
       System.out.print("\tScore "+countSc+": "); 
       scores [j] = key.nextInt(); 
       } 
      } 
    } 
    public static void showNamesScores(){ 
     System.out.println(""); 
     for (int i = 0; i < names.length; i++){ 
      System.out.print(names [i]+"\t"); 
      for (int j = 0; j < scores.length; j++){ 
       System.out.print(scores [j]+" "); 
      } 
     } 
    } 
} 

輸出的樣本

多少名字和得分 N> 2 S> 2 名稱1:最大 評分1:2 評分2:4 名稱2:麥克 評分1:3 評分2:2

max 3 2 mike 3 2

回答

0

你的scores數組使得只有一個名字的分數。您應該將其更改爲二維數組。

static int [][] scores = null; 
... 
names = new String [numNa]; 
scores = new int [numNa][numSc]; 
... 
public static void readNameScores(){ 
    for (int i = 0; i < names.length; i++){ 
    System.out.print("Name "+(i+1)+": "); 
    names [i] = key.next(); 
    for (int j = 0; j < scores.length; j++){ 
     System.out.print("\tScore "+(j+1)+": "); 
     scores[i][j] = key.nextInt(); 
    } 
    } 
} 
+0

如果超過兩個名字和分數? –

+0

@PouriaMohseni只要每個名字的分數相同,相同的代碼應該可以工作。 – Eran