Tristan
Tristan

Reputation: 7

Accessing Strings in other methods created by JOptionPane?

I'm trying to use a string created by JOptionPane in another JOptionPane. I tried making the string global. Am I doing this correctly?

import javax.swing.JOptionPane;


public class Dialogue
{
    public static String reason = "";
    public static void main(String[] args)
{
    ask();
    JOptionPane.showInputDialog("You're here because: " + reason);
}

public static void ask()
{
    String reason = JOptionPane.showInputDialog("Why are you here?");
}
} 

Upvotes: 0

Views: 475

Answers (3)

Zied R.
Zied R.

Reputation: 4964

the string reason is declarted as global and static variable, so ther is no need to redelrated is ask () method

public class Dialogue
{
    public static String reason = "";
    public static void main(String[] args)
{
    ask();
    JOptionPane.showInputDialog("You're here because: " + reason);
}

public static void ask()
{
     reason = JOptionPane.showInputDialog("Why are you here?");
}
} 

enter image description here enter image description here

Upvotes: 1

exexzian
exexzian

Reputation: 7890

remove String from ask method (as by doing so you are creating a new local variable reason )

keep it as

reason = JOptionPane.showInputDialog("Why are you here?");

Upvotes: 1

Hugo Sousa
Hugo Sousa

Reputation: 1926

In this statement:

String reason = JOptionPane.showInputDialog("Why are you here?");

You're creating a new String. So the global variable and this one aren't referencing the same String.

Do it like this:

reason = JOptionPane.showInputDialog("Why are you here?");

This way you're using the global variable, as you want.



EDIT: I guess that you don't want an user input after asking why he's there, so I guess you would like to switch this:

JOptionPane.showInputDialog("You're here because: " + reason);

to this

JOptionPane.showMessageDialog(null, "You're here because: " + reason);

This way, it just gives an information, and doesn't wait for an user input.

Upvotes: 1

Related Questions