java如何在两个不同的方法中使用相同的变量,而不使这些变量成为全局变量?
我的简单程序将要求用户输入几个城市。用户应该能够通过选择其他选项打印出来
现在我在一个方法(city();
)中声明了一个数组来存储这些值。我有两种不同的方法,分别询问用户和打印出(这将在主类中调用)。如果我想在printCity()
method中打印数组(),它必须使用另一个方法(city();
)中使用的变量。因此,printCity()
方法显示了找不到变量的错误。此外,在我的情况下(I不知道为什么)将这些变量声明为全局(在方法之外)不起作用。
那么,我如何解决这个问题,使相同的变量在两种不同的方法中工作
我的代码: 主要类别:
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: ");
}
}
}
}
用户输入类:
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
}
}
}
# 1 楼答案
听起来
city()
方法应该返回城市数组,然后可以将其传递给printCity()
方法:在你的电话号码中:
我也强烈建议你重新考虑你的名字。例如,IMO认为
getFavoriteCities()
和displayCities()
更合适# 2 楼答案
您需要将它作为方法参数传递
那就这样说吧
# 3 楼答案
假设“global”指的是将它们声明为UserInput类的字段(如果你指的是其他内容,请纠正我),我无法理解你为什么不想这么做
考虑到您在同一类的同一实例的两个方法之间共享数据,一个字段正是您所需要的
我冒昧地重写了UserInput类,将数组作为字段(主类的工作方式不变)。还要注意的是,你不需要传递城市的数量,因为它是由数组的长度决定的