2016-05-05 350 views
1

我正在編寫一門需要教師班級大小的代碼,然後創建一個包含姓名和成績的數組。這個想法是讓代碼按他們的分數排序(不是他們的名字)。我的問題是,我似乎無法使得數據的分數部分增加一倍。基本上,代碼只需要int輸入。取得學生姓名和成績並按順序排列的代碼

我希望代碼在完成後執行此操作。

你班上有多少學生? 6

  1. 名稱:湯姆·史密斯

    得分:82.5

  2. 名稱:瑪麗·史密斯

    得分:92.5

  3. 名稱:愛麗絲瀑布

    得分: 61

  4. 名稱:琳達·紐森

    得分:73

  5. 名稱:傑克·特納

    得分:89.3

  6. 名稱:喬治·布朗

    得分:52

這是我到目前爲止有:

import java.util.*; 
public class FinalJamesVincent { 
    public static void main(String[] args) { 
     Scanner input = new Scanner(System.in); 
     System.out.print("Enter the number of students: "); 
     int numofstudents = input.nextInt(); 
     String[] names = new String[numofstudents]; 
     double[] array = new double[numofstudents]; 
     for(int i = 0; i < numofstudents; i++) { 
      System.out.print("Name: "); 
      names[i] = input.next(); 
      System.out.print("Score: "); 
      array[i] = input.nextInt(); 
     } 
     selectionSort(names, array); 
     System.out.println(Arrays.toString(names)); 
    } 
    public static void selectionSort(String[] names, double[] array) { 
     for(int i = array.length - 1; i >= 1; i--) { 
      String temp; 
      double currentMax = array[0]; 
      int currentMaxIndex = 0; 
      for(int j = 1; j <= i; j++) { 
       if (currentMax > array[j]) { 
        currentMax = array[j]; 
        currentMaxIndex = j; 
       } 
      }  
       if (currentMaxIndex != i) { 
        temp = names[currentMaxIndex]; 
        names[currentMaxIndex] = names[i]; 
        names[i] = temp; 
        array[currentMaxIndex] = array[i]; 
        array[i] = currentMax; 
       } 
     }  
    } 
} 
+4

使用'nextDouble'而不是'nextInt'來獲得'double'而不是'int'。 – resueman

+0

我明白你是否是初學者,但更好的方法是製作一個「學生」班。並將它們存儲到可以分類的'Student []'中。 –

回答

3
array[i] = input.nextInt(); 

nextInt()解析輸入到一個整數,採取double輸入,你應該使用input.nextDouble()

將其替換爲array[i] = input.nextDouble();這將使它完美。

+0

謝謝,我知道它一定很簡單。 –