我有一项家庭作业,我们必须为健身中心制作一个非常基本的控制台应用程序,可以创建成员(member)和员工。当我要求用户输入新成员的生日时,出现了我的问题。它应该检查生日是否采用 DD/MM/YY 格式,因此我检查给出的答案是否为 6 位数字,并且仅 6 位数字。这似乎有效,除非有人给出以 0 开头的出生日期,例如:090498。
System.out.println("Please enter the new members birthday, in the format of DD/MM/YY:");
this.birthdate = console1.nextInt();
while(String.valueOf(birthdate).length() != 6){
System.out.println("Please give a valid date of birth in the format of: DD/MM/YY");
this.birthdate = console1.nextInt();
}
它不会给出错误消息,但仅在生日为 6 位数字且以 1 EG 开头时才完成循环:190798。
我知道这可能很简单,但我大约一个月前才开始学习 CS :)
最佳答案
正如其他答案告诉您的那样,如果您以 0 开头 int,代码将忽略它。您可以导入 SimpleDate 并使用 String 来使用它。我在这里留下了另一个问题的链接,也许可以为您提供更多帮助。 [链接]How can I convert an Integer (e.g 19000101 ) to java.util.Date?
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateEXE {
public static void main(String[] args)throws Exception {
String DateT="31/12/1998";
Date NDate=new SimpleDateFormat("dd/MM/yyyy").parse(DateT);
System.out.println(DateT+"\t"+NDate);
}
}
希望有帮助。
关于java - 检查字符串中的数字,当字符串以 0 开头时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58505033/