[英]Is there a command in java to make the program go back to the beginning of a loop
[英]Java - Go back to beginning of program flow if condition failed
就像我写这篇文章一样,我可以想像这个问题有多么基本,但是我在这里..
我有一个Java客户端,其中我验证用户输入的“日期”输入,如果有效,则将其传递给其他地方。 我正在使用JOptionPane显示输入对话框。
基本上,当用户输入了无效的日期格式时,我的程序退出了,用户必须再次重新启动程序。 取而代之的是,我希望在显示“输入无效日期”消息之后显示弹出的输入对话框,这是将控制权再次传递给该行代码的最佳方法是什么?
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Properties;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.swing.JOptionPane;
public class Client {
static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
public static void main(String[] args) throws IOException, ParseException {
Properties prop = new Properties();
InputStream IP = null;
// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
IP = new FileInputStream("Client.properties");
prop.load(IP);
String host = prop.getProperty("ServerIP");
String port = prop.getProperty("Port");
int port1 = Integer.parseInt(port);
Socket s = new Socket(host, port1);
String reportDate = JOptionPane.showInputDialog("Enter Date:");
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
/**
* User Input Validation
*/
if (reportDate.matches("^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$")) {
out.println(reportDate);
s.close();
System.exit(0);
} //if
else {
String Error = "INCORRECT date format entered!";
JOptionPane.showMessageDialog(null, Error);
} //else
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (IP != null) {
try {
IP.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
在成功情况下使用System.exit(0)
时,只需将代码包装在while (true) { }
的无限循环中即可。
做这样的事情(伪代码):
String reportDate = "badDate";
while (!reportDate.matches("^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$"))
{
//do all the things that are currently in your if statement
}
我知道这与您要查找的响应没有直接关系。 实际上,对您问题的直接答案是使用循环,它将按您期望的方式工作。
但是,如果要选择日期,则应考虑使用Java SwingX 。
SwingX库具有很多好的组件,包括出色的日期选择器
我认为这可以帮助您取得有效的Date
:
Date reportDate;
do {
try {
String str = JOptionPane.showInputDialog("Enter Date:");
reportDate = new SimpleDateFormat("yyyy-MM-dd").parse(str);
break;// loop break when got a valid date e.g. 2016-09-16
} catch (Exception mistake) {
System.err.println("Invalid input: " + mistake);
}
} while (true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.