如何为Java成绩管理程序添加及格/不及格判断逻辑?
Solution: Add Pass/Fail Logic to Your Grade Management Program
Got it, let's get this sorted for you! The perfect spot to add your pass/fail check is in the printAverageGrade() method—since that's where you're already calculating and displaying the average grade.
Here's the step-by-step fix:
- First, store the calculated average in a variable (this makes your code cleaner and avoids re-calculating the average multiple times).
- Add your
if-elsestatement right after printing the average to check if it's below 80, then output the corresponding result.
Modified printAverageGrade() Method
private void printAverageGrade() { double average = getAverage(subjects); // Store average in a variable System.out.println("Total of grades: " + getSum(subjects)); System.out.println("Count of grades: " + subjects.length); System.out.println("Your average grade is: " + average); // Your pass/fail logic here if (average < 80) { System.out.println("failed"); } else { System.out.println("passed"); } System.out.println(); }
Optional: Combine Output into One Line
If you prefer to show the average and result in a single line, you can adjust the code like this:
private void printAverageGrade() { double average = getAverage(subjects); System.out.println("Total of grades: " + getSum(subjects)); System.out.println("Count of grades: " + subjects.length); // Combine average and result in one print statement System.out.print("Your average grade is: " + average + " - "); if (average < 80) { System.out.println("failed"); } else { System.out.println("passed"); } System.out.println(); }
Why This Works
The issue you were facing is that you can't embed an if statement directly inside a System.out.print() call—if is a control flow statement, not an expression you can inline like that. By first storing the average in a variable, you can easily reference it in your condition check and output the result separately.
内容的提问来源于stack exchange,提问作者user8572431
相关产品推荐
相关产品推荐

