I'm trying to declare the values of variables using method 1, and then take that information from method1 to calculate a variable in method 2.
how exactly would I go about doing so? Scanners are being used to evaluate arguments.
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) {
stockPrice = sharesOwned * costPerShare;
allShareValue = numShares * costPerShare;
System.out.println("Cost per-share: " costPerShare);
System.out.println("Stock price: " stockPrice);
System.out.println("All Share Total: " allShareValue);
}
public void sellStock(int numShares,int sharesSold) {
sharesOwned = sharesOwned - sharesSold;
System.out.println(sharesOwned);
}
}
CodePudding user response:
What do you mean by "Method 1" and "Method 2"? Can you be more specific?
Anyway, if you want to get values from a method, you have to make sure that it is not a void method.
CodePudding user response:
2 ways:
1- Method1 must return a value that is going to be used by method2. Then method2 invokes method1 and uses the returned value.
2- Using a field in the class where the methods belong to store the computed value by method1. Then method2 may use the value of that field. If the only purpose of the field is to store the computed value by method1, the field should be declared private.