0

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?");
}
} 
Tristan
  • 7
  • 4

3 Answers3

1

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.

Hugo Sousa
  • 1,904
  • 2
  • 15
  • 28
  • Thank you. The reason I am waiting for an input is because I do not know how to continue after a message dialog. Would I just request another input after? – Tristan Feb 22 '14 at 01:54
1

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?");
exexzian
  • 7,782
  • 6
  • 41
  • 52
1

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

Zied R.
  • 4,964
  • 2
  • 36
  • 67