简体   繁体   English

比较和循环未按预期工作

[英]Comparing and Loop not Working as Expected

I am writing a program in Java, which basically find the number of days between 2 specific dates. 我正在用Java编写程序,基本上可以找到2个特定日期之间的天数。 The user inputs two dates in DD/MM/YYYY format, and I take the sub strings of the day/month/year and calculate the number of days between the 2. I also did a sort of validation, where if the format is wrong (for example d/mm/yyyy) then the person has to re-write the date in the right format. 用户以DD / MM / YYYY格式输入两个日期,然后我采用日/月/年的子字符串并计算两次之间的天数。我还进行了一种验证,如果格式错误, (例如d / mm / yyyy),那么此人必须以正确的格式重写日期。 I did this by making sure that the / in the date are in their right position. 我这样做是为了确保日期中的/正确位置。 If the 4 / match, then a boolean variable gives me true, and the program continues, if not it gives me false and it asks for the date again. 如果4 /匹配,则布尔变量使我为true,然后程序继续运行;否则,程序继续为false,并再次要求输入日期。

The problem is that it is always giving me false, and even then, it is not re-looping back. 问题在于它总是给我错误,即使那样,它也不会重新循环。

import java.util.*;
 public class DateDifference {
 int day1, day2, month1, month2, year1, year2;
 String startdate, enddate, day1S, day2S, month1S, month2S, year1S, year2S;
 String datevalidation = "/";
 boolean dval;
public static void main(String args[]){
    DateDifference difference = new DateDifference();
}
DateDifference() {
    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();

    Scanner sc = new Scanner (System.in);
    do {
    System.out.println("Enter Start Date [dd/mm/yyyy]:");
    startdate = sc.next();
    System.out.println("Enter End Date [dd/mm/yyyy]:");
    enddate = sc.next();

    int l1 = startdate.length();
    int l2 = enddate.length();
    day1S = startdate.substring(0,2);
    month1S = startdate.substring(3,5);
    year1S = startdate.substring(6,l1);

    day2S = enddate.substring(0,2);
    month2S = enddate.substring(3,5);
    year2S = enddate.substring(6,l2);

    if (startdate.substring(2,3).equals(datevalidation) & startdate.substring(5,6).equals(datevalidation) & enddate.substring(2,3).equals(datevalidation) & enddate.substring(5,6).equals(datevalidation)) 
        dval = true;

    else 
        dval = false;
        System.out.println("Wrong date format. Try again");

   } while (dval = false);

   day1 = Integer.parseInt(day1S);
   month1 = Integer.parseInt(month1S);
   year1 = Integer.parseInt(year1S);
   day2 = Integer.parseInt(day2S);
   month2 = Integer.parseInt(month2S);
   year2 = Integer.parseInt(year2S);

    cal1.set(year1, month1 - 1, day1); 
    cal2.set(year2, month2 - 1,day2);
    System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));
}
public int daysBetween(Date cal1, Date cal2){
    return (int)( (cal2.getTime() - cal1.getTime()) / (1000 * 60 * 60 * 24));
}

} }

Here are some images on how it is working: 以下是有关其工作方式的一些图片:

When input is correct: http://vvcap.net/db/2100RYdaSM1T6EXLqgq5.png 输入正确时: http : //vvcap.net/db/2100RYdaSM1T6EXLqgq5.png

When input is not correct: http://vvcap.net/db/9qSEwDKSTIdLAWmxS_Cy.png 输入不正确时: http : //vvcap.net/db/9qSEwDKSTIdLAWmxS_Cy.png

When not correct, it just gets stuck when its trying to make 1/ in an integer, which I can understand. 当不正确时,它会在尝试使1 /成为整数时卡住,据我所知。

Any help? 有什么帮助吗?

Thanks a lot. 非常感谢。

Your problem, from what I see, is when you are taking the substring() of the dates. 从我的角度来看,您的问题是当您使用日期的substring()时。 You are checking to see if the position equals "/" BUT you are taking 2 positions (hence the error showing that the string you are converting to and int is "1/" from the error code. 您正在检查位置是否等于“ /”,但是您要占据2个位置(因此错误显示错误代码表明您要转换为int且int的字符串为“ 1 /”。

Try changing all the If statement line looks like the following: 尝试更改所有的If语句行,如下所示:

From

 if (startdate.substring(2,3).equals(datevalidation) & startdate.substr...
       dval = true;
 ...

To

 if ( !startdate.substring(2,3).contains(datevalidation) &
      !startdate.substring(5,6).contains(datevalidation) &
      !enddate.substring(2,3).contains(datevalidation) &
      !enddate.substring(5,6).contains(datevalidation)) 
       dval = true;
 ...

AND the while() statement should be == not just = . AND while()语句应为==而不是= You're setting it rather than checking on each iteration of the loop. 您是在设置它,而不是检查循环的每次迭代。

Rather than checking if 2 characters equals 1 character (eg "1/".equals("/")) you are now checking to see if those 2 characters DO NOT contain the separator. 现在,不是检查2个字符是否等于1个字符(例如“ 1 /”。equals(“ /”)),而是要检查这2个字符是否不包含分隔符。

Also you want want a checker or a try-catch block just in-case the two digits entered are not numeric to stop the NumberFormatExcpetion from returning. 另外,如果输入的两个数字不是数字,以防止NumberFormatExcpetion返回,您还希望使用检查程序或try-catch块。

Hope this helps 希望这可以帮助

You have a typo in this row 您这一行有错字

 } while (dval = false);

operation dval = false is always false so your do .. while runs only once. 操作dval = false始终为false因此您只do .. while运行一次时do .. while I think you meant to use 我想你打算用

 } while (dval == false);

to have real loop. 有真正的循环。


To verify the loop behavior you can run this test and look what happens: 要验证循环行为,您可以运行此测试并查看会发生什么:

@Test
public void testLoop() {

    int iteration = 0;
    boolean flag;
    do {
        flag = false; // unused assignment
        ++iteration; // iteration counter
        System.out.println( "Running iteration " + iteration );
    } while ( flag = false );

    System.out.println( "Loop finished. Total number of iterations is " + iteration );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM