首页 文章

如何在不使这些变量全局的情况下在两种不同的方法中使用相同的变量?

提问于
浏览
0

我的简单程序会要求用户进入几个城市 . 用户应该能够通过选择其他选项将其打印出来 .

现在我在方法( city(); )中声明了一个数组来存储这些值 . 我有两种不同的方法,分别用于询问用户并将其打印出来(这将在主类中调用) . 如果我想打印出数组(在 printCity() 方法中),它必须使用在另一个方法( city(); )中使用的varibale . 因此, printCity() 方法显示无法找到变量的错误 . 此外,将这些变量声明为Global(在方法之外)在我的情况下不起作用(我不知道为什么) . So, how can I fix this issue so that same variables works in two different methods?

我的代码:主要类:

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类:

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

        }


    }
}

3 回答

  • 1

    假设通过'global',你的意思是将它们声明为UserInput类的一个字段(如果你的意思是其他的话,请纠正我),我不明白为什么你不想这样做 .

    考虑到您在同一个类的同一个实例的两个方法之间共享数据,一个字段正是您所需要的 .

    我冒昧地重写你的UserInput类,让数组作为一个字段(主类不变) . 另请注意,您无需传递城市数量,因为它取决于数组的长度 .

    public class UserInput {
        private String[] cityInArr;
    
        public void city() {
            System.out.println("How many favourite city you have in your list?");
            Scanner inScanner = new Scanner(System.in);
            int numOfCity = inScanner.nextInt();
            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("\nThese are your favorite cities: ");
            for (int j = 0; j < cityInArr.length; j++) {//has an error
                System.out.printf("%s ", cityInArr[j]);//has an error
            }
        }
    }
    
  • 0

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

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

    在你的调用代码中:

    String[] cities = {}; // Empty until fetched
    
    ...
    cities = ui.city();
    ...
    ui.printCity(cities);
    

    我还强烈建议您重新审视您的命名 . 例如, getFavoriteCities()displayCities() 会更合适,IMO .

  • 0

    您需要将其作为方法参数传递 .

    public void printCity(String[] cityInArr, int numOfCity) {
    
    
            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
    
            }
    

    然后这样称呼它

    public static void main(String[] args) {
         .......
         printCity(cityArray, numOfCity);
         ........
        }
    

相关问题