java - 是否可以基于 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);
}
}
}
`
解决方案
使用 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 。
推荐阅读
- ios - iOS 上工具栏项中的图像是白色的(Xamarin 表单)
- c++ - 如何让不同的线程一起填充一个数组?
- java - InvocationRequest.setInteractive() 在 maven-invoker-3.0.1 中不存在
- spring-boot - 虚拟机和 IDE 上的 Docker 和临时工作/开发
- blazegraph - 如何在 Blazegraph 中插入带有 POST 请求正文的 SPARQL 数据?
- python - 在 Django 中处理不同但相似的模型层次结构的最佳方法是什么?
- java - 从已部署的 jar 访问 web-inf
- angular - 从 TypeScript 设置输入元素的值
- swift - 核心数据。按日期过滤
- php - 从 Laravel 中的更多表中检索数据的最佳方法