Java程序需求:打印血红蛋白计数及对应评估结果
Solution to Include Haemoglobin Count in Output
Got it, let's adjust your code so the printed output includes the actual haemoglobin count alongside the assessment result. The key issue right now is that your displayHaemoglobin method only receives the result string—it doesn't have access to the original count value. Here's how to fix it step by step:
Key Modifications:
- Update the
displayHaemoglobinmethod to accept two parameters: the haemoglobin count (as anint) and the result string - Adjust the method calls in
mainto pass both the count and the result - Tweak the print statement to match your desired output format
Modified Code:
package oopsconcepts; public class ReturnMethod { public static void main(String[] args) { int count1 = 12; String result1 = findHaemoglobin(count1); displayHaemoglobin(count1, result1); int count2 = 8; String result2 = findHaemoglobin(count2); displayHaemoglobin(count2, result2); } public static String findHaemoglobin(int count) { String result; if (count <= 8) { result = "Very Low"; } else if (count <= 10) { // No need for upper bound check here since we already handled <=8 result = "Low"; } else if (count <= 12) { result = "OK, Can be improved"; } else if (count <= 15) { result = "Excellent"; } else { result = "NA"; } return result; } public static void displayHaemoglobin(int count, String result) { System.out.println("Haemoglobin count of " + count + " signifies " + result + ". "); } }
Explanation:
- Parameter Addition: By adding
int counttodisplayHaemoglobin, we can directly reference the original count value when printing. - Cleaner Condition Checks: I simplified the
if-elseconditions infindHaemoglobin—since we check conditions from lowest to highest, we don't need to repeat the lower bound (e.g., once we've handledcount <=8, the next condition only needscount <=10to cover values 9-10). - Desired Output: The print statement now formats the text exactly as you requested—for input
12, it will output:Haemoglobin count of 12 signifies OK, Can be improved.
内容的提问来源于stack exchange,提问作者ameya garge
相关产品推荐
相关产品推荐

