2016-02-21 31 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