2015-11-23 77 views
0

我有這個程序,要求用戶輸入學生和他們的得分。然後顯示得分最高和最低的學生的名字。我的問題是我的程序不會打印最低分數。Java數組diplay最低學生

任何幫助將不勝感激。 下面是我的代碼。

private Scanner n; 
private int limit; 
private String[] names; 
private int[] scores; 

public Exercise9() { 

    n = new Scanner(System.in); 
    limit = 0; 

    index(); 
} 

public void index() { 

    int counter = 0; 

    System.out.print("Enter how many students : "); 
    limit = Integer.parseInt(n.nextLine()); 

    names = new String[limit]; 
    scores = new int[limit]; 

    while(counter < limit && limit != 0) { 

     System.out.print("Enter name : "); 
     names[counter] = n.nextLine(); 

     System.out.print("Enter score : "); 
     scores[counter] = Integer.parseInt(n.nextLine()); 

     counter += 1; 

    } 

    if(limit == 0) { 
     System.out.print("\n\nNo student(s) to display ."); 
    } else { 
     displayStudents(); 
    } 
} 

public void displayStudents() { 

    System.out.print("\n\nDisplay list of student(s) and scores : \n"); 

    for(int x = 0 ; x < limit ; x++) { 
     System.out.println("\t" + names[x] + "\t" + scores[x]); 
    } 

    System.out.print("\n\nHighest : " + getHighest() + "\t\tLowest : " + getLowest()); 
} 

public String getHighest() { 

    int theScore = 0; 
    String theName = ""; 

    for(int x = 0 ; x < scores.length; x++) { 
     if(scores[x] > theScore) { 
      theScore = scores[x]; 
      theName = names[x]; 
     } 
    } 
    return theName; 
} 

public String getLowest() { 

    int theScore = 0; 
    String theName = ""; 

    for(int x = 0 ; x < scores.length; x++) { 
     if(scores[x] < theScore) { 
      theScore = scores[x]; 
      theName = names[x]; 
     } 
    } 
    return theName; 
} 

public static void main(String[] args) { 

    new Exercise9(); 
} 

回答

1

要初始化您的變量theScore爲零,以在getLowest()開始。假設你不會有負分,這將永遠不會得到更新。

嘗試初始化theScore至任意高的號碼。

0

設置你theScorescores之一,試試這個:

public String getLowest() { 

    int theScore = scores[0]; 
    String theName = ""; 

    for(int x = 0 ; x < scores.length; x++) { 
     if(scores[x] < theScore) { 
      theScore = scores[x]; 
      theName = names[x]; 
     } 
    } 
    return theName; 
} 
0

只是跟蹤最低分數及其指標。如果你初始化最低得分第一的學生,不要再檢查學生 - 在1

public String getLowest() { 

     int theScore = scores[0]; 
     int lowest = 0; 

     for(int x = 1 ; x < scores.length; x++) { 
      if(scores[x] < theScore) { 
      theScore = scores[x]; 
      lowest = x; 
      } 
     } 
     return names[lowest]; 
    } 

開始循環當然修改getHighest以同樣的方式()