Search code examples
javaswingjoptionpane

JOptionPane.showInputDialog is only showing up once


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

public class moneyRate {

    public static void main(String[] args) {
        //Get Inputs
        Scanner input = new Scanner(System.in);
        JOptionPane.showInputDialog("How many old pounds? ");
        double oldPounds = input.nextDouble();
        JOptionPane.showInputDialog("How many old shillings? ");
        double oldShillings = input.nextDouble();
        JOptionPane.showInputDialog("How many old pennies? ");
        double oldPennies = input.nextDouble();

        input.close();

        //New Pounds calc
        double newPounds = ((oldPounds*160.80) + (oldShillings*8.04) + (oldPennies*0.67));

        System.out.print("Your old pounds shillings and pennies are equal to £4"
                + "" + newPounds + ".");
    }
}

In a programming class we were asked to make a program that would tell the user how much their old pounds shillings and pennies are worth in today's pounds. I had this fully working using the console as input and output for the program, but now when I try to do it using JOptionPane, to present the user with small pop-up boxes it won't work. When I run the task only the first pop-up shows and the program just ends without any form of error message. I'm assuming this is a simple mistake with syntax but I can't spot it.

If anyone spots the mistake, please help me out, thanks :)


Solution

  • The way you are using JOptionPane and Scanner cause the issue.

    JOptionPane.showInputDialog("How many old pounds? "); // display this
    double oldPounds = input.nextDouble(); // then it wait for scanner input
    

    Now your program will hold there for expecting input from console. You need to change your code as follows

     double oldPounds = Double.parseDouble(JOptionPane.showInputDialog("How many old pounds? "));
     double oldShillings = Double.parseDouble(JOptionPane.showInputDialog("How many old shillings? "));
     double oldPennies = Double.parseDouble(JOptionPane.showInputDialog("How many old pennies? "));
    
     double newPounds = ((oldPounds*160.80) + (oldShillings*8.04) + (oldPennies*0.67));
    
     System.out.print("Your old pounds shillings and pennies are equal to £4"
                + "" + newPounds + ".");