java - 用 do while 循环提示,似乎无法进入循环

标签 java

我正在努力让代码的“do/while循环”部分正常工作。我必须使用它,因为它是作业的一部分。我的目标是在无效输入时引导用户返回输入。日期的有效输入格式为 mm/dd/yyyy。因此,如果用户输入 2292014,我想向他显示错误消息并提示他重新输入日期。

我对 Java 编码非常陌生,但我知道我离这个问题的正确解决方案已经不远了。如果可以的话,请提供帮助!

String date; //user entered date
int slash1; //position of the first slash
int slash2; //position of the second slash
boolean isValid; // true if date is valid
String day; // day part of the input date becomes a separate string
String month; // month part of the input date becomes a separate string
String year; // year part of the input date becomes a separate string
isValid = true; //initializing to true
do
{
  System.out.print("Enter a date (mm/dd/yyyy on or after 1860, such as 3/10/2015): ");
  date = stdIn.next(); //storing the input date
  slash1 = date.indexOf('/'); //position of the first slash in the user string
  slash2 = date.indexOf('/', slash1+1); //it looks for the position of the second string after the first one
  if (slash1 >= 0 && slash2 >= 0 && slash2 > (slash1+1))
  {
    month = date.substring(0, slash1);
    day = date.substring(slash1+1, slash2);
    year = date.substring(slash2+1);
    for (int i = 0; i < month.length(); i++)
    {
      if (!(Character.isDigit(month.charAt(i))))
      isValid = false;
    }
    for (int i = 0; i < day.length(); i++)
    {
      if (!(Character.isDigit(day.charAt(i))))
      isValid = false;
    }
    for (int i = 0; i < year.length(); i++)
    {
      if (!(Character.isDigit(year.charAt(i))))
      isValid = false;
    }
  } System.out.println("Invalid date: " + date + ". Please re-enter.");
} while (isValid == false);

最佳答案

while 循环的条件是

isValid=false

我想你的意思是

isValid==false

关于java - 用 do while 循环提示,似乎无法进入循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29189986/

相关文章:

java - 在 Android 应用程序中使用 DrawerLayout 时手势不起作用

java - 读取用户输入时如何使用 boolean 变量

java - 如何使用私钥将 .pfx 文件转换为 keystore ?

java - 我们可以将菱形运算符的结果与原始构造函数区分开来吗?

java - 谷歌应用引擎中的 Json

java - 在 Android 中将 WifiManager 重铸为对象时遇到问题

java - 场景切换后保持舞台最大化

java - 使用Spring Boot配置Kafka的问题

java - 如何正确关闭与 mysql 服务器的 hibernate session

java - Spring Boot 2 升级java.lang.ClassNotFoundException : EmbeddedServletContainerCustomizer