gpt4 book ai didi

Java 程序跳过询问用户输入

转载 作者:行者123 更新时间:2023-12-01 18:22:37 26 4
gpt4 key购买 nike

我正在尝试向用户询问日期和时间。在我的程序中,我有方法询问用户这些值和方法来验证输入。然而,在我的程序中,用户永远无法输入日期值,因为程序继续经过该点并采用空值作为日期。为什么是这样?因此,验证方法会导致错误:

java.lang.NullPointerException

“主要”

    public void bookAppointment(BankClient bc) {
String date = askForDate();
String time = askForTime();
sendAppointmentNotification(createAppointmentNotification(date,time));
}

询问日期方法

    private String askForDate() {
GetInputFromUserInter input = new GetInputFromUser();
while(true) {
String date = input.getUserInput("Date For Appointment in the form of DD/MM/YYYY");
date.trim();
if (validateDate(date)) {
return date;
}
else {
System.out.println(date+" is Invalid Date format");
}
}
}

验证日期方法

    private static boolean validateDate(String date) {
System.out.println("here");
SimpleDateFormat sdfrmt = new SimpleDateFormat("DD/MM/YYYY");
sdfrmt.setLenient(false);
try{
Date javaDate = sdfrmt.parse(date);
}
/* Date format is invalid */
catch (ParseException e){
return false;
}
/* Return true if date format is valid */
return true;
}

获取输入法

    static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
public String getUserInput(String label) {
String value = null;
System.out.println( "\nProvide " + label + ":" );
System.out.println( ">" );

while(value !=null) {

try {
value = input.readLine();
}

catch (IOException ex) { ex.printStackTrace(); }
}
return value;
};

最佳答案

您的程序跳过用户输入的原因是您在 getUserInput() 方法中初始化 String value = null ,然后有效地说 while null ! = null 这是 false,因此您的 while 循环永远不会执行。我会像这样修改代码:

String value = "";
System.out.println( "\nProvide " + label + ":" );
System.out.println( ">" );

while(value.equals("")) {

try {
value = input.readLine();
}

catch (IOException ex) { ex.printStackTrace(); }
}
return value;

然后,如果用户只是垃圾邮件输入而不输入任何内容,它会不断提示他输入一些内容。

关于Java 程序跳过询问用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60279018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com