[英]A simple program issue with java loops
我對我的代碼有一個簡單的問題。 我對Java很陌生,嘗試自我學習,但是我現在陷入了循環。 在我看來,這應該可行。 問題也是要問一些學生,然后讓用戶輸入每個學生的姓名和分數。 然后,它應該顯示得分最高的學生和第二名的學生。 出於某種原因,我的代碼僅顯示了我輸入的第一名和第二名的名字和分數。 我可能犯了一個大錯誤,但也許有人可以指出我正確的方向嗎? 抱歉,這看起來像是一團糟。 :(
public class Chapter4_9 {
public static void main(String[] args) {
//scanner for input
Scanner input = new Scanner(System.in);
//ask user for number of students
System.out.print("Enter the number of students: ");
int numberStudents = input.nextInt();
//declare variables
double highestScore = 0;
double tempScore = 0;
double secondHighestScore = 0;
String firstStudent = "";
String tempStudent = "";
String secondStudent = "";
for (int i = 0; numberStudents != i; ++i) {
System.out.print("Enter the students name followed by his score: ");
String studentName = input.next();
double studentScore = input.nextDouble();
if (i == 0){
firstStudent = studentName;
highestScore = studentScore;
}
else if (studentScore > highestScore) {
tempStudent = firstStudent;
studentName = firstStudent;
secondStudent = tempStudent;
tempScore = highestScore;
studentScore = highestScore;
secondHighestScore = tempScore;
}
}
System.out.println("The highest scoring student is " + firstStudent + " with a " + highestScore);
System.out.println("The second highest scoring student is " + secondStudent + " with a " + secondHighestScore);
}
}
這個塊似乎有點混亂:
else if (studentScore > highestScore) {
tempStudent = firstStudent;
studentName = firstStudent;
secondStudent = tempStudent;
tempScore = highestScore;
studentScore = highestScore;
secondHighestScore = tempScore;
}
此阻止的預期結果是什么? 當您再也無法再次讀取studentName
和studentScore
的值時(在從用戶那里讀取新值之前),為什么要覆蓋它們的值?
大概的目的是用最高的分數/名稱替換第二個分數/名稱,然后用當前輸入替換最高的分數/名稱-但這根本不是代碼所要做的。 這樣做:
secondStudent = firstStudent;
secondScore = highestScore;
firstStudent = studentName;
highestScore = studentScore;
完全不需要臨時變量。
但是,僅此更改是不夠的。 您還需要考慮新分數不高於當前最高分數,但高於當前第二最高分數的情況。 我讓你去解決需要什么...
順便說一句,如果為“名稱/分數”組合引入了單獨的類,例如Student
,則代碼可能會更簡單。 然后,您將沒有並行變量-只需擔心topStudent
, secondStudent
和currentStudent
即可。
當您發現分數更高時,您的代碼是錯誤的。
secondStudent = fistStudent; // what used to be high score is now 2nd
firstStudent = studentName;
// score adjustment left for you to do ;)
代碼中有一個錯誤,並且您沒有涵蓋所有內容。
在for循環中,您必須具有以下這些:
else if (studentScore > highestScore) {
secondStudent = firstStudent;
firstStudent = studentName;
secondHighestScore = highestScore;
highestScore = studentScore;
}
else if (studentScore < highestScore && studentScore > secondHighestScore) {
secondStudent = studentName;
secondHighestScore = studentScore;
}
做完了
您的邏輯不正確。 您沒有處理所有方面。 如果檢查您的代碼,它將僅能正確處理第一個輸入,而這完全取決於您提供輸入的方式。 您的邏輯有待改進。 不需要那么多的臨時變量。
最好在調試模式下運行您的應用程序,然后逐步進入它,以便知道它出了什么問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.