Reputation: 157
This is my code:
public void viewFlight() {
int select;
String option;
String newOrigin = null;
viewFlightOrigin();
}
public void viewFlightOrigin() {
option = console.nextLine();
switch (select) {
case 1:
System.out.println("=======================================");
System.out.println("city of origin: Melbourne");
System.out.println("=======================================");
newOrigin = "Melbourne";
break;
// ...
}
}
How to use local variables in the viewFlight()
to be used again in the viewFlightOrigin()
without declaring the variables in the field or re-declaring again in the viewFlightOrigin()
?
Upvotes: 2
Views: 429
Reputation: 21
Only instance variables are available across different methods. Local variable are having scope till that method not out side of the method.
Upvotes: 0
Reputation: 3456
Using parameter:
public void viewFlight() {
int select;
String option;
viewFlightOrigin(select, option);
}
public void viewFlightOrigin(int select, String option) {...}
Upvotes: 0
Reputation: 27
1.
public void viewFlight()
{
.....
viewFlightOrigin(option);
....
}
2.declare a instance field then it's not a local variable
Upvotes: 0
Reputation: 726987
The easiest thing to do if you do not need to modify the variable would be to pass it down as a parameter to the function:
viewFlightOrigin(newOrigin);
public void viewFlightOrigin(String option) {
// ...
}
If you need to modify the variable, you can return the new value from the method:
newOrigin = viewFlightOrigin(origin);
public String viewFlightOrigin(String option) {
// ...
}
Upvotes: 1
Reputation: 236122
If you need to use and modify the same "variables" in two different methods, then they must not be local variables, they're instance attributes of the class.
Alternatively, you could pass them as parameters to viewFlightOrigin()
, just remember that any modification to the variables inside viewFlightOrigin()
will not be visible after the method returns back to viewFlight()
.
Upvotes: 2