You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中getNetSalary方法返回值未生效问题咨询(是否需要实例化对象?)

Why Your 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 computed netSalary value.
  • We store that returned value in calculatedNetSalary (you could name this variable anything, like netSalary if 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 00:27:33