![](/img/trans.png)
[英](Java) How Do I Sort Numbers From Least to Greatest and Assign Them to Variables?
[英]How can I sort the data in a loop from least to greatest if the data gets replaced each time it goes back into the loop?
我有一個程序,應該像這樣。 您輸入班級的學生人數,例如說3個。 因此,您輸入一個學生ID,后跟4個數字。 前三個是平均成績占總班級成績的80%,第四個數字是學生在參加期末考試后希望獲得的成績,占總成績的20%。
Example:
Enter number of students in class: 3
(Here you would enter the data)
123456 90 90 90 90
543216 70 80 80 70
435366 80 80 80 90
然后輸出應該是:
123456 90 //(The minimum score the student must get on their final to get the grade they want)
435366 130
543216 44
我把所有的數學知識都弄下來了,而且效果很好。 輸入信息后,我會得到正確的數字。 我遇到的問題是要以從最小到最大的順序顯示輸出。 我使用表格輸入信息,其中“行”是班上的學生人數,“列”是5(ID,1、2、3,期望的年級)
for (int count = 0; count < numberOfStudents(in this case, 3); ++count)
{
StudentID = The first ID I entered (123456);
Grade = *a bit of math to solve for this*;
}
現在,當它再次進入循環時,將替換StudentID和Grade的值,因此我無法將它們與任何值進行比較以檢查哪個值小於哪個值。 我本來想將StudentID放入一個數組中,然后進行比較,但是后來我遇到的問題是弄清楚如何獲得與ID相對應的成績。
有任何想法嗎?
聽起來確實應該創建一個Student
類,其中包含其ID,其結果和所需的最終成績。 然后,您可以擁有一個學生集合(例如, Student[]
或List<Student>
並使用Collections.sort
對現有結果進行排序。(要使排序比較成績,可以使Student
實現Comparable<Student>
,或者編寫實現Comparator<Student>
的GradeComparator
。)
作為一般原則,只要發現自己有多個集合,則當一個集合的每個元素對應於其他集合的相同元素索引時,應考慮將數據封裝為一種類型,然后封裝為該類型的集合。 因此,再舉一個例子,而不是:
String[] addressLines1;
String[] addressLines2;
String[] cities;
String[] zipCodes;
String[] countries;
...您將擁有一個Address[]
或List<Address>
,其中Address
類具有第1行,第2行,城市,郵政編碼和國家/地區的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.