Java中getNetSalary方法返回值未生效问题咨询(是否需要实例化对象?)
getNetSalary Return Isn't Working (And No, You Don't Need to Instantiate an Object) Hey there! Let's clear up your confusion right away:
The Core Issue: You're Not Calling the Method!
Your getNetSalary method does work correctly and its return netSalary; statement is totally valid. The problem is that in your main method, you never actually run the getNetSalary method after reading the grossSalary value. You've written all the logic to calculate net salary, but you haven't told your program to execute that logic!
Do You Need to Instantiate an Object? Nope!
Since getNetSalary is marked as static, you don't need to create an instance of MortgageDecision to use it. Static methods belong to the class itself, not to individual objects, so you can call them directly from within the same class (or using the class name from other classes).
How to Fix Your Code
Here's how to modify your main method to call getNetSalary and use its returned value:
package mortgage; import java.util.Scanner; public class MortgageDecision { public static void main(String[] args) { double grossSalary; Scanner input = new Scanner(System.in); System.out.print("Gross Annual Salary: £"); grossSalary = input.nextDouble(); // Call the getNetSalary method and store its returned value double calculatedNetSalary = getNetSalary(grossSalary); // Print the result to see it work System.out.println("Net Annual Salary: £" + calculatedNetSalary); input.close(); // Don't forget to close your Scanner resource! } // ... your existing getNetSalary method stays exactly the same ... }
Quick Breakdown of the Fix
- We add a line to call
getNetSalary(grossSalary): this passes the user-input gross salary to your calculation method, runs all the tax logic, and retrieves the computednetSalaryvalue. - We store that returned value in
calculatedNetSalary(you could name this variable anything, likenetSalaryif you prefer). - Finally, we print out the result so you can see the returned value in action.
Your return netSalary; was always doing its job—you just never gave it a chance to run by invoking the method!
内容的提问来源于stack exchange,提问作者sheeve92

