Home > database >  Global variable can't store value
Global variable can't store value

Time:12-26

I've been trying to input a String value from the user and store it into a global variable. 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.

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. 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. 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?

CodePudding user response:

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

CodePudding user response:

Global variables are the variables that can be accessed anywhere in the java program. 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.

  • Related