2012-12-06 33 views
0

我試圖做的是搜索「gradePsd」數組找到最高年級,如果有兩個等級相同的值,則將學生的姓名打印到控制檯。查找和打印高數字數組方法Java

我遇到的問題是,這種方法是採取數組的第一個索引值並打印它,因爲它是第一次通過時的高值,如果第二個值比第一個大,那麼它也會打印等。

所以我的問題是如何才能打印出高分的學生。

public static void hiMarkMethod(String[] NamePsd, int[] gradePsd) 
{ 
    String nameRtn = ""; 
    int num = gradePsd[0]; 

    System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are:"); 

    for (int i = 0; i < gradePsd.length; i++) 
    { 
     if (gradePsd[i] >= num) 
     { 
      num = gradePsd[i]; 
      nameRtn = NamePsd[i]; 
     } 

     System.out.print(nameRtn + ", "); 
    } 
} 

回答

0

先找到最多 然後用這個數字

public static void hiMarkMethod(String[] NamePsd, int[] gradePsd) 
    { 

    String nameRtn = ""; 
    int num = gradePsd[0]; 

    System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are:"); 
    //find the highest number 
    for (int i = 0; i < gradePsd.length; i++){ 
    if (gradePsd[i] >= num){ 
     num = gradePsd[i]; 
    } 
    //print students with that number 
    for (int j = 0; j < NamePsd.length; j++){ 
     if (gradePsd[j] == num) 
     { 
      nameRtn = NamePsd[j]; 
      System.out.print(nameRtn + ", "); 
     } 
    } 

可能的解決方案1000打印一個學生。

+0

非常感謝你,這工作像一個夢... –

0

初始化num與-1並採取System.out出來的for循環。但是你只能用你的代碼來確定一個學生。如果您想存儲多個名稱,則需要nameRtnCollection

事情是這樣的:

public static void hiMarkMethod(String[] NamePsd, int[] gradePsd) { 
    Collection<String> namesRtn = new ArrayList<String>(); 
    int num = -1; 

    for (int i = 0; i < gradePsd.length; i++) { 
     if (gradePsd[i] > num) { 
      num = gradePsd[i]; 
      namesRtn.clear(); // clear name list as we have a new highest grade 
      namesRtn.add(NamePsd[i]); // store name in list 
     } else if (gradePsd[i] == num) { 
      namesRtn.add(NamePsd[i]); // if a second student has the same grade store it to the list 
     } 

    } 
    System.out.println ("\n\nThe Student(s) with Hightest Mark(s) are: " + namesRtn); 
}