![](/img/trans.png)
[英]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.