Search code examples
javajoptionpane

Java, programming a Currency Calculator, stops at first JOptionPane and keeps running


Im a fresh student trying to learn Java programming. This week we have an assignment to program a currency calculator using two classes. Im having some issues while running the program, namely keeping it going. We have to use JOptionPane to ask for input and show output, and Im not entirely sure how Im supposed to keep them "popping up". Im hoping that I could get some pointers in how Im supposed to keep the program running.

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

public class runner {
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

        do
            {
                JOptionPane.showInputDialog(null, "Type in the number of kroner you want to check: ");
                double kroner = input.nextInt();
                Object[] options = {"Euro", "Yen"};
                int choice = JOptionPane.showOptionDialog(null, "you wrote: " + kroner + "do you want to convert this to euro or yen?", "Choose an alternative", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);

            Functions operationObject = new Functions();

            if (choice == 0)
            {
                operationObject.kronerTilEuro(kroner);
            }
            else if (choice == 1)
            {
                operationObject.kronerTilYen(kroner);
            }
            else
            {
                JOptionPane.showMessageDialog(null, "You need to pick one of the alternatives!");
            }
        }
        while (!input.hasNextInt());
        {
            JOptionPane.showMessageDialog(null, "I am not happy");
            input.next();
        }
    }
}

Ive to tried to create a loop so that the first panel will show up again if the user gives input that is not an integer, but without any luck. Please let me know if there is something that Ive missed.


Solution

  • the problem is here , you are using a showInputDialog reading sth from user , after that you have a input.nextInt() without any warn in your program , it waits for you until you enter a number :

    JOptionPane.showInputDialog(null, "Type in the number of kroner you want to check: ");
    double kroner = input.nextInt();
    

    first replace input.nextInt() with input.nextDouble(), you are reading a double not a int

    i'll tell you two ways :

    1 - replace the showInputDialog with showMessageDialog :

    JOptionPane.showMessageDialog(null, "Type in the number of kroner you want to check: ");
    double kroner = in.nextDouble();
    

    2 - try to read with showInputDialog and parse it's String to Double

    double kroner = Double.parseDouble(JOptionPane.showInputDialog(null, "Type in the number of kroner you want to check: "));