Armando Frias
Armando Frias

Reputation: 59

Why won't the dialog box come up when I run this code in Eclipse?

Please see my code below, why won't the input dialog box come up in Eclipse when I run the program?

package cookieTest;
import javax.swing.JOptionPane;
import java.util.Scanner;

public class CookieCalories
{
    public static void main(String[] args)
{
        Scanner input = new Scanner(System.in);
        int cookiesEaten = input.nextInt();
        int caloriesPerCookie = 300 / 4;
        int calorieIntake = cookiesEaten * caloriesPerCookie;

        JOptionPane.showInputDialog("How many cookies did you eat?");

        System.out.print("Your calorie intake was: " + calorieIntake);

        input.close();
        System.exit(0);
    }
}

Upvotes: 0

Views: 1098

Answers (1)

Susannah Potts
Susannah Potts

Reputation: 827

So in this case, how you're calling the input dialog and getting the data is not correct, it should look like this:

int cookiesEaten = Integer.parseInt(JOptionPane.showInputDialog(null, "How many cookies did you eat?"));

You don't need a scanner when using the JOptionPane.showInputDialog() function as the input dialog handles the scanner. As for the leading null parameter, because we're not dealing with a custom built Swing GUI, we don't have a parent. But Java expects one, calling it explicitly and giving it the null parent allows it to open the pane. (Without it, the program just hangs there forever it seems).

EDIT: Keep in mind, JOptionPane takes some time to open the window sometimes. (roughly 10-15 seconds for me).

Your code should look like this:

package cookieTest;
import javax.swing.JOptionPane;
import java.util.Scanner;

public class CookieCalories
{
    public static void main(String[] args)
    {
        int cookiesEaten = Integer.parseInt(JOptionPane.showInputDialog(null, "How many cookies did you eat?"));
        int caloriesPerCookie = 300 / 4;
        int calorieIntake = cookiesEaten * caloriesPerCookie;

        System.out.print("Your calorie intake was: " + calorieIntake);

        System.exit(0);
    }
}

Upvotes: 1

Related Questions