首页 > 解决方案 > 是否可以基于 if 语句进行循环?

问题描述

如果用户在输入输入后单击“否”,我正在尝试让我的代码循环。

import java.awt.event.WindowAdapter;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

    public class Sizer extends WindowAdapter 
    {
            public static void main (String[]args){


            JFrame m = new JFrame();
            JOptionPane.showMessageDialog(m,"Ok To set the window size you are going to type in the number for each value REMEMBER THE SIZE IS IN PIXELS");


            String input1= JOptionPane.showInputDialog("Height (suggested under 1080 and above 300)");
            int Height= Integer.parseInt( input1);

在此输入之后,我必须确认此用户是否正确输入,如果他们单击是,它会继续,如果他们单击否,它会退出我希望它让用户再次输入它我该怎么做?

        int a1 = JOptionPane.showConfirmDialog(m,"Are you sure that this is the correct Height"+ Height);
        if (a1==JOptionPane.YES_OPTION){
        if (a1==JOptionPane.NO_OPTION){

        }

        String input2= JOptionPane.showInputDialog("Width (suggested under 1920 and above 300)");
        int Width = Integer.parseInt( input2);




        JFrame frame = new JFrame();                    
        Slop comp = new Slop();
        frame.add(comp);
        frame.setSize(Height,Width);
        frame.setTitle("Slop of a Line");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
                }   
        }
}           

`

标签: javaloopsif-statement

解决方案


使用 do...while 循环,如果用户单击“否”,则清除高度

public class Sizer extends WindowAdapter 
{
    public static void main (String[]args){

        JFrame m = new JFrame();
        int height = 0;

        JOptionPane.showMessageDialog(m,"Ok To set the window size you are going to type in the number for each value REMEMBER THE SIZE IS IN PIXELS");

        do {
            String input1= JOptionPane.showInputDialog("Height (suggested under 1080 and above 300)");
            height= Integer.parseInt(input1);
            int a1 = JOptionPane.showConfirmDialog(m,"Are you sure that this is the correct Height "+ height);

             if (a1==JOptionPane.NO_OPTION){
                height = 0;
            }

        } while (height==0)
    }

}

这假定高度必须 > 0。如果高度可以为 0,则使用 -1 作为初始值并改为重置值。

编辑:

@Nicholas K 的回答表明您实际上并不需要该 if 语句,而是像这样完成 while 循环:

            a1 = JOptionPane.showConfirmDialog(m,"Are you sure that this is the correct Height "+ height);

        } while (a1==JOptionPane.NO_OPTION)

但是,要这样做,您需要在方法的开头初始化 a1 。


推荐阅读