简体   繁体   English

全局变量不能存值

[英]Global variable can't store value

I've been trying to input a String value from the user and store it into a global variable.我一直在尝试从用户输入一个String值并将其存储到一个全局变量中。 The input works well inside the method where I instance it, but the problem is that if I try to call the global variable from another method, its value is set back to null .输入在我实例化它的方法中运行良好,但问题是如果我尝试从另一个方法调用全局变量,它的值将设置回null

Here's my code for the input:这是我的输入代码:

Object select;
select = JOptionPane.showInputDialog(this, "Choisissez le département : ", "Boîte de dialogue",
JOptionPane.QUESTION_MESSAGE, icone, liste, liste[0]);
this.select = select.toString();

At this point, if I print this.select in the console, its value is properly shown.此时,如果我在控制台中打印this.select ,它的值就会正确显示。 Now when I call it from elsewhere:现在,当我从其他地方调用它时:

public void afficherInfos() throws IOException {
//some code
d = new Dep(Integer.parseInt(liste.get(Arrays.asList(d.getDeps()).indexOf(this.getSelect()))));
}

It shows an IndexOutOfBoundsException since indexOf(this.getSelect()) returns -1 , as the program can't find it in the array.它显示IndexOutOfBoundsException ,因为indexOf(this.getSelect())返回-1 ,因为程序无法在数组中找到它。 When I print this.getSelect() inside of this method, the console shows null , but I can't see how it is possible to lose the value, as it was correctly instantiated and stored?当我在此方法中打印this.getSelect()时,控制台显示null ,但我看不出如何丢失该值,因为它已正确实例化和存储?

i think it seems to be related promotion and type casting i know when we print some instance with console, that instance printed with toString(), but you use this.getSelect() in indexOf我认为这似乎与提升和类型转换有关我知道当我们用控制台打印一些实例时,那个实例用 toString() 打印,但是你在 indexOf 中使用 this.getSelect()

Global variables are the variables that can be accessed anywhere in the java program.全局变量是java程序中任何地方都可以访问的变量。 Global variables are not technically allowed in Java. Since Java is object-oriented, everything is part of a class. A static variable can be declared, which can be available to all instances of a class. Well, in your case you can use this.getSelect() in indexOf. Java 在技术上不允许使用全局变量。由于 Java 是面向对象的,因此所有内容都是 class 的一部分。可以声明 static 变量,它可用于 class 的所有实例。好吧,在你的情况下你可以使用这个.getSelect() 在 indexOf 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM