My simple program will ask user to enter few cities. The user should be able to print them out by choosing another option.
Now I have declared an array inside a method (city();
) to store those values. And I have two different methods each for asking user and printing them out (which is gonna be called in main class). If I want to print out the array (in printCity()
method ), it must use the varibale which is used in another method ( city();
). Thus, the printCity()
method shows error that it can't find the variables. Besides, declaring those variable as Global (outside the methods)doesn't work in my case (I don't know why).
So, how can I fix this issue so that same variables works in two different methods?
My code: Main class:
package city;
import java.util.*;
public class City {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
UserInput ui = new UserInput();
System.out.println(" THIS PROGRAM WILL TELL YOU THE CITY YOU HAVE EVER TRAVELLED\n"
+ " Choose one of the following option\n\n"
+ " You must enter city name before printing them out!");
System.out.println("1. Enter the cities you have travelled\n"
+ "2. Print out the cities\n"
+ "3. Exit\n"
+ "....................\n"
+ "....................");
while (true) {
int userChoose = input.nextInt();
switch (userChoose) {
case 1:
//call method where the program asks to enter city name
ui.city();
break;
case 2:
//call method where the program prints out the city name
ui.printCity();
break;
case 3:
System.exit(0);
default:
System.out.println("Invalid input! Plz try again: ");
}
}
}
}
UserInput class:
package city;
import java.util.*;
public class UserInput {
Scanner inScanner = new Scanner(System.in);
public void city() {
System.out.println("How many favourite city you have in your list?");
int numOfCity = inScanner.nextInt();
String[] cityInArr = new String[numOfCity];
for (int i = 0; i < numOfCity; i++) {
System.out.println("City " + (i + 1) + ": ");
cityInArr[i] = inScanner.next();
}
System.out.println("YOU ARE DONE! NOW PRINT THEM OUT");
}
public void printCity() {
System.out.println("");
System.out.println("These are your favorite cities: ");
for (int j = 0; j < numOfCity; j++) {//has an error
System.out.printf("%s ", cityInArr);//has an error
}
}
}
It sounds like your city()
method should return the array of cities, which you can then pass to the printCity()
method:
public String[] city() {
...
return cityInArr;
}
public void printCity(String[] cities) {
...
}
And in your calling code:
String[] cities = {}; // Empty until fetched
...
cities = ui.city();
...
ui.printCity(cities);
I would also strongly recommend that you revisit your naming. For example, getFavoriteCities()
and displayCities()
would be more appropriate, IMO.
See more on this question at Stackoverflow