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

时间:2015-03-22 01:29:27

标签: 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);

3 个答案:

答案 0 :(得分:2)

你的while循环条件是

isValid=false

我认为你的意思是

isValid==false

答案 1 :(得分:0)

我认为至少有一个与do {} while()循环无关的问题是你从未在循环中将isValid变量设置为true。它开始是真的,但是如果你输入一个无效的日期,程序将再次提出问题,但它不会回到假设它是真的。 CyanogenCX也是正确的,你需要双等号来测试相等性,而不是单一的用于分配。尝试更改说明的行:

isValid=true;

从do do循环中的“do”之前到它之后的行。

答案 2 :(得分:0)

您是否使用设置为if (slash1 >= 0 && slash2 >= 0 && slash2 > (slash1+1))的断点调试代码?并单步执行它(例如,在Eclipse中使用[F6])?

isValid永远不会成为false,无论您输入有效日期还是无效日期,只要它包含数字:1/1/199/99/99.

只有在您输入字母isValid时,

false才会变为a/1/1

此外,每次都会显示错误消息,因为它不依赖于isValid

还有一些事情需要改进。我可以建议去https://codereview.stackexchange.com/吗?