Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JOptionPane YES_NO_OPTION

I'm having some problems with a very basic, beginner level Java program. I have a function which should return a value dependent on a user's response to a JOptionPane YES_NO_OPTION message box. The program runs just fine until you are presented with the option of starting again, or of backing out. No matter which option you choose, yes, or no, it takes you back to do a new loop. I know one way to fix this would simply be to rely on a cancel button, but I want to understand why this code isn't returning the values I expect it to, so would be very grateful for your help.

import javax.swing.JOptionPane;

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

        for (int i = 0; i < 3000; i++) {
            double Int1 = optiontakeshape();
            double Int2 = optiontakediam();
            if (Int1 == 1.0) {
                Shape s1 = new Circle(Int2);
                infoBox(s1.area2d());
            } else {
                Shape s1 = new Sphere(Int2);
                infoBox(s1.volume());
            }
            int yesno = repeat();
            if (yesno == 1) {
                System.out.println(yesno);
                break;
            }
        }
    }

    public static int repeat() {
        int j;
        int g = JOptionPane.YES_NO_OPTION;
        JOptionPane.showConfirmDialog(null, "Would you like to begin again?",
                "Repeat?", g);
        if (g == JOptionPane.NO_OPTION) {
            j = 1;
            System.exit(0);
        } else if (g == JOptionPane.YES_OPTION) {
            j = 2;
        } else {
            j = 3;
            System.exit(0);
        }
        System.out.println(j);
        return j;
    }
    //...
}

EDIT: Thank you for the many swift responses. I wasn't actually testing the value of the Yes/No result. The code I have now implemented is:

public static int repeat ()
        {
        int j;
        if (JOptionPane.showConfirmDialog(null, "Would you like to begin again?", "Repeat?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){
            j = 2;
        } else {
            j = 1;
            //System.exit(0); escaped so I could test the break point was working properly
        }
        System.out.println(j);
        return j;
        }
like image 243
Orphid Avatar asked Dec 03 '25 22:12

Orphid


1 Answers

This is your problem.

int g = JOptionPane.YES_NO_OPTION;

g will always be YES_NO_OPTION, which in in terms of integer values is the same as YES_OPTION. Both are 0.

Instead try this

int g =  JOptionPane.showConfirmDialog(null, "Would you like to begin again?", "Repeat?", JOptionPane.YES_NO_OPTION);
like image 156
Paul Samsotha Avatar answered Dec 06 '25 12:12

Paul Samsotha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!