gpt4 book ai didi

java - 如何在两个不同的方法中使用相同的变量而不将这些变量设为全局变量?

转载 作者:行者123 更新时间:2023-12-01 12:02:05 24 4
gpt4 key购买 nike

我的简单程序将要求用户输入几个城市。用户应该能够通过选择其他选项来打印它们。

现在我在方法 (city();) 中声明了一个数组来存储这些值。我有两种不同的方法,分别用于询问用户打印它们(这将在主类中调用)。如果我想打印出数组(printCity() 方法中),它必须使用在另一个方法中使用的变量( city();)。因此,printCity() 方法显示错误,指出它无法找到变量。此外,将这些变量声明为全局变量(在方法之外)在我的情况下不起作用( 不知道为什么)。那么,如何解决这个问题,以便相同的变量在两种不同的方法中工作?

我的代码:主类:

    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

}


}
}

最佳答案

听起来您的 city() 方法应该返回城市数组,然后您可以将其传递给 printCity() 方法:

public String[] city() {
...
return cityInArr;
}

public void printCity(String[] cities) {
...
}

在您的调用代码中:

String[] cities = {}; // Empty until fetched

...
cities = ui.city();
...
ui.printCity(cities);

我还强烈建议您重新审视您的命名。例如,在我看来,getFavouriteCities()displayCities() 会更合适。

关于java - 如何在两个不同的方法中使用相同的变量而不将这些变量设为全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27923124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com