gpt4 book ai didi

java - 无法访问我的阵列

转载 作者:行者123 更新时间:2023-12-01 13:15:44 25 4
gpt4 key购买 nike

我的程序是使用 Java 创建一个火车路线查找器,首先作为命令行程序,然后转换为 GUI。这是我目前最不担心的事情。我目前停留在系统的一项功能上,那就是显示用户之前输入的两个车站之间的车站列表。

现在,我已经能够提示用户选择他们的停靠点(代码中的第 3,149 - 3,171 行):

if(deptChoice == 1 && arrChoice == 2){

List<String> stopList1_2 = new ArrayList<String>();
Scanner stopPick = new Scanner(System.in);
stopPick.useDelimiter(System.getProperty("line.separator"));

do {
System.out.println("\nCurrent list of stops between Leicester to Loughborough is:\n\n" + stopList1_2);
System.out.println("\nWould you like to add a new stop? (Please enter 'Yes' or 'No')\n");

if (stopPick.next().startsWith("Yes")) {
System.out.println("\nPlease type in the stop you wish to add to the route:\n");
stopList1_2.add(stopPick.next());
}

else {
break;
}

} while (true);

String[] stopArr1_2 = stopList1_2.toArray(new String[0]);
System.out.println("\nCurrent stops between Leicester to Loughborough is:\n\n" + Arrays.toString(stopArr1_2));

}

他们输入的停靠点将添加到数组中。当他们对车站之间的车站数量感到满意时,循环就会结束,并显示车站 X 和车站 Y 之间的车站数组。

但是,问题来了:

然后,我想访问之前创建的数组,并在我的代码中包含所有精确的停止点。在这个“if”语句中,如果满足,那么我希望显示数组(stopArr1_2)(第3,019 - 3,021行):

if(deptChoice == 1 && arrChoice == 2){
System.out.println(""); //this should be where I call the array back to display itself
}

因为这些站点将对应于用户选择 deptChoice == 1(车站 1 = 莱斯特)到 arrChoice == 2(车站 2 = 拉夫堡)。

我希望这一点很清楚:

我基本上希望用户输入的车站数组在他们选择火车路线时重新出现。

这是我在 Notepad++ 中编写的完整代码,我认为对你们来说,看到我的所有代码而不是小段代码会更好,并且它已被注释。

此外,为了理解我的问题,请运行我的程序。要了解我的问题,请执行以下操作:

1)编译Train.java(javac Train.java)

2)运行程序(java Train)

3) 选择管理菜单(编号 5)

4) 选择输入菜单(编号 1)

5) 选择任意两个电台

6) 输入几个站点,直到您满意为止

7)当它显示这两个车站的最终停靠站数组时,程序似乎结束了,希望这不是问题

8)再次运行程序(java Train)

9)选择火车路线(第3号)

10) 按照与之前相同的顺序选择相同的电台,这样它就会找到您刚刚创建的数组

11)现在什么也不会出现,因为,这就是我的问题。我不知道如何重新获得我刚刚为其制作的数组。

下载我的 Train.java 文件(以及 Train.txt 文件,如果需要)的链接:

https://www.dropbox.com/s/7dy0pp9vyykwhrk/TrainJava.rar

有什么建议吗?

最佳答案

你的第二个代码块的位置是什么? (您所说的需要访问 List<String> stopList1_2 的代码)?

1 如果它在同一个类中,但在不同的方法中,则

移动此声明 List<String> stopList1_2 = new ArrayList<String>(); (当前在您的第一个代码块中)到类字段。

但是

2 如果它与您的第一个代码块在同一个类中并且在同一个方法中,那么

移动此声明 List<String> stopList1_2 = new ArrayList<String>(); (当前在 if 代码语句内)到 if 之外条件。

但请将此视为解决您手头问题的快速方法。更重要的是 - 请阅读variable scoping rule and access specifiers in java .

关于java - 无法访问我的阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22490092/

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