Можно ли сделать цикл, основанный на операторе if? - PullRequest
0 голосов
/ 06 сентября 2018

Я пытаюсь запустить цикл кода, если пользователь нажимает нет после ввода своих данных.

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);
                }   
        }
}           

`

Ответы [ 2 ]

0 голосов
/ 06 сентября 2018

Используйте цикл 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 каквместо этого начальные и сбрасываемые значения.

РЕДАКТИРОВАТЬ:

@ Ответ Николаса К показывает, что на самом деле вам не нужен оператор if, вместо этого просто завершите цикл while следующим образом:

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

        } while (a1==JOptionPane.NO_OPTION)

Для этого вам нужно инициализировать a1 в начале метода.

0 голосов
/ 06 сентября 2018

Вы можете использовать

    int a1 = 0;
    do { 
      // Read input till user says 'yes
      a1 = JOptionPane.showConfirmDialog(m, "Are you sure that this is the correct Height "+ Height);
    } while (a1 == JOptionPane.NO_OPTION);

Таким образом, цикл продолжает работать, пока пользователь не введет значение JOptionPane.NO_OPTION

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...