Java中return关键字的正确使用及Person类growOlder方法修正问题
Fixing Your Person Class's
growOlder Method Let's walk through the issues in your code and fix them to match your requirements—you're almost there!
Key Problems in the Current growOlder Method
- Wrong return type: The method is declared to return
int, but your requirement specifies it should return aboolean(true when age is updated, false otherwise). This is why you were forced to returnnYears(to avoid compilation errors), which caused the extra numbers in your output. - Hardcoded age increment: You're adding
13directly instead of using the passednYearsparameter. The requirement says to increase age by the value ofnYears(when it's non-negative). - Incorrect output handling: You're printing
true/falseinside the method, but the requirement expects the method to return these values so the caller can handle printing (which is why your output has extra digits from the returnednYears).
Corrected Full Person Class
public class Person{ private String name; private int age; // Removed unused `getOlder` field since it wasn't being used public Person(){ this("Otto", 25); } public Person( String name, int age ){ this.name = name; this.age = age; } public String getName(){ return name; } public int getAge(){ return age; } // Fixed growOlder method public boolean growOlder(int nYears){ if(nYears >= 0){ age += nYears; // Use the passed parameter instead of hardcoding 13 return true; // Return true instead of printing it } else { return false; // Return false without modifying age } } public String toString( ){ return getName() + " " + getAge(); } }
Explanation of Changes
- Return type updated: Changed
public int growOlder(...)topublic boolean growOlder(...)to align with the requirement of returning a true/false status. - Dynamic age increment: Replaced
age = age + 13withage += nYearsso the age increases by the actual value passed to the method (e.g., 13 during your test). - Return boolean values directly: Removed the
System.out.printlncalls inside the method. Instead, we returntrueorfalse—when you call this method from your test code, you can print the returned value, which will give you the clean output you expect. - Cleaned up unused code: Got rid of the
private int getOlderfield since it wasn't serving any purpose.
Test Output Verification
If you run test code like this:
public class Main { public static void main(String[] args) { Person person = new Person(); System.out.println(person); // Prints "Otto 25" System.out.println(person.growOlder(13)); // Prints "true", age becomes 38 System.out.println(person); // Prints "Otto 38" System.out.println(person.growOlder(-13)); // Prints "false", age stays 38 System.out.println(person); // Prints "Otto 38" } }
You'll get exactly your expected output:
Otto 25 true Otto 38 false Otto 38
内容的提问来源于stack exchange,提问作者M Ann
相关产品推荐
相关产品推荐

