Java同一类内不同方法之间如何传递变量信息?
Java方法间传值及Scanner参数接收实现方案
你现有代码的核心问题是thisStock方法存在参数遮蔽:形参名和类成员变量名完全相同,方法内默认读取的是形参,没有完成成员变量的赋值,调整后按以下方案实现即可:
步骤1:修正参数遮蔽问题并补充Scanner调用逻辑
调整后的完整可运行代码如下:
import java.util.Scanner; public class StockB { public String coName; public int sharesOwned; public double costPerShare; public int numShares; public double stockPrice; public double allShareValue; public double sharesSold; public void thisStock(int numShares, double costPerShare, int sharesOwned) { // 用this关键字明确为成员变量赋值,避免参数遮蔽 this.numShares = numShares; this.costPerShare = costPerShare; this.sharesOwned = sharesOwned; this.stockPrice = this.sharesOwned * this.costPerShare; this.allShareValue = this.numShares * this.costPerShare; System.out.println("每股成本: " + this.costPerShare); System.out.println("持有股票总价值: " + this.stockPrice); System.out.println("全部股票总价值: " + this.allShareValue); } public void sellStock(int sharesSold) { this.sharesOwned = this.sharesOwned - sharesSold; System.out.println("剩余持有股份数:" + this.sharesOwned); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); StockB stock = new StockB(); // 接收用户输入的初始化参数 System.out.print("请输入总股份数:"); int numShares = scanner.nextInt(); System.out.print("请输入每股成本:"); double costPerShare = scanner.nextDouble(); System.out.print("请输入当前持有股份数:"); int sharesOwned = scanner.nextInt(); // 先调用thisStock完成所有成员变量赋值 stock.thisStock(numShares, costPerShare, sharesOwned); // 接收卖出参数,调用sellStock直接读取已赋值的成员变量计算 System.out.print("请输入要卖出的股份数:"); int sharesSold = scanner.nextInt(); stock.sellStock(sharesSold); scanner.close(); } }
实现说明
- 你定义的
sharesOwned、costPerShare等属性都属于类的成员变量,是实例的全局属性,只要在同一个实例的任意方法中完成赋值,其他方法都可以直接读取该值,不需要额外传参 - 如果需要跨实例传值,可以将
thisStock方法的返回值改为自定义封装类,将需要传递的参数打包后返回,再将返回对象作为入参传入sellStock方法即可
内容的提问来源于stack exchange,提问作者yikes
相关产品推荐
相关产品推荐

