JAVA中若输入的格式不对再次返回重新输入的命令
时间: 2024-03-09 15:46:53 浏览: 10
在Java中,可以使用循环结构来实现输入格式不正确时重新输入的功能。可以使用do-while循环,让用户输入日期,然后验证日期格式是否正确,如果不正确要求用户重新输入,直到输入正确为止。以下是一个实现的例子:
```
import java.text.SimpleDateFormat;
import java.util.Scanner;
public class DateValidator {
public static void main(String[] args) {
String dateFormat = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Scanner scanner = new Scanner(System.in);
String inputDate;
do {
System.out.print("请输入日期(格式为" + dateFormat + "):");
inputDate = scanner.nextLine();
try {
sdf.parse(inputDate);
} catch (Exception e) {
System.out.println("日期格式不正确,请重新输入!");
inputDate = "";
}
} while (inputDate.equals(""));
System.out.println("输入日期为:" + inputDate);
}
}
```
在上面的例子中,我们使用Scanner类来获取用户输入的日期字符串。然后使用do-while循环,不断要求用户输入日期,直到输入的日期格式正确为止。在每次循环中,我们使用try-catch语句来验证输入的日期格式是否正确,如果不正确,则输出错误信息并要求用户重新输入。如果输入的日期格式正确,循环结束,并输出输入的日期。