Reputation: 188
I am making a Calculator and have the classes called addition, subtraction, multiplication and division and another class called Calculation and need them all to take the data from Calculation and then change it's Operator an example of the code:
public static void addition(){
calculation(); //imports calculation
for(int counter=0; counter < list.size(); counter++){
answer += list.get(counter);
}
System.out.println("The sum of these numbers is " + answer);
}
I simplified my Calculation class so it's easier to understand:
public static void calculation(){
List<Double> list = new ArrayList<Double>();
do{
list.add(scan.nextDouble());
}while(true)
After this I want to be able to use the List in my Addition class yet I keep getting errors on list that say "list cannot be resolved" and it wants me to create a local variable. I want it to take the list from Calculation and then allow me to change it's outcome.
How can I allow it to use 'list' in my Addition class?
Upvotes: 0
Views: 88
Reputation: 27336
Okay, so I think that you have a fundamental misunderstanding of how Java methods work. When you call calculation()
, you're going to execute the code in the method, then return to the same point in addition()
.
Now, list
is declared inside calculation()
, so the scope of list
is inside that method. It can't be used outside of that method. As soon as calculation()
is finished, it will destroy list
. If you want to access list
after calculation()
is finished, then you should return
it.
return list;
Then you can access it in your addition
method as follows:
List<Double> list = calculation();
Edit
I've noticed that in your calculation()
method, you've got an infinite loop:
do{
list.add(scan.nextDouble());
}while(true)
This will keep expecting a new double from the user. This is not desirable because the user isn't going to want to add an infinite series of double
values together. Mainly because that's impossible. And parsing like that will only cause problems. I would recommend parsing the input as a String
, checking if the value corresponds to a double
and then parse it using the Double.parseDouble()
method.
Extra Reading
I would read into returning data in Java. Check it out here.
I would also look into Scope. Scope is a fundamental principle in most programming languages, so its best that you develop a good grasp on it. Read about it here.
Finally, I would look at method calls. You seem to think that a method call imports the code, rather than executes it. Read about it here.
Upvotes: 2