【问题标题】:I am trying to work, on this. Checking if this actually works?我正在为此努力。检查这是否真的有效?
【发布时间】:2017-03-17 14:29:49
【问题描述】:

我不确定这是否真的有效,所以我只是想询问并确认,这是否是显示数字的正确方式以及我是否会得到输出,哪些不同的出生日期。

这个程序有点笨拙。

    int day = 0;
    int month = 00;
    int year = 1979;

    while(day<33 && month<14 && year<2005 && year>1978)
    {
        if(day==32)
        {
            day = 0;
        }

        if(month==13)
        {
            month = 00;
        }

        if(year==2004)
        {
            year = 1979;
        }

        String dob = new String(day+""+month+""+year);
        System.out.println(dob);
        if(dob=="2611983")
        {
            System.out.println("My birthday");
            break;
        }

        day++;
        month++;
        year++;
    }

【问题讨论】:

  • 不要将字符串与== 进行比较。而不是dob=="2611983",而是dob.equals("2611983")
  • 您是否得到了一些异常或意外的输出?
  • 好的,谢谢@Hugo。祝你有美好的一天。
  • @Hugo,先生,再次感谢您。

标签: java confirmation


【解决方案1】:

当你运行它时会发生什么? 一些预测:它不会像你期望的那样做,因为你在同一个循环运行中增加日、月和年。 它也将永远循环,因为您在循环中重置了日、月和年。 经过很多循环后,它可能会遇到你生日的星座,但并不像想象的那样。 让它运行并尝试了解会发生什么。

【讨论】:

  • 所以我让它运行了相当长的一段时间,但即使在击中之后,它也没有多大作用。谢谢,不过,我会努力的。再次感谢您,先生。
【解决方案2】:

这将无法正常工作,因为您同时增加了日、月和年(即您没有检查所有天),而是尝试这样做:

int day = 1;
int month = 1;
int year = 1979;
bool done=false;
while(!done)
{
 if(year==2004)
 {
        year = 1979;
 }
 while (month<13 && !done)
 {
    while (day<32 && !done)
    {
        String dob = new String(day+""+month+""+year);
        System.out.println(dob);
        if(dob.equals("2611983"))
        {
         System.out.println("My birthday");
         done=true;
        }
        day++;  
    }
    day=1;
    month++;    
 }
    month=1;
    year++;
}

【讨论】:

  • 太棒了,这是一个完美的代码。谢谢!但是我不太明白这背后的逻辑,为什么你是'day=0'和'month++',而在另一个循环中,'month=0'和'year++'。很抱歉,如果这个问题不是一个经过深思熟虑的问题,但希望你能回答这个问题来解决我的问题。感谢您的代码和时间。祝你有美好的一天。
  • @lafeo_007 没注意,谢谢指出,我更正了
  • 没问题,事实上,对于上面我输入的代码,日期和月份都是“0”。再次感谢您,祝您有美好的一天。
猜你喜欢
  • 1970-01-01
  • 2015-02-07
  • 2021-03-03
  • 1970-01-01
  • 2019-11-10
  • 2016-08-30
  • 1970-01-01
  • 2020-06-12
  • 2012-01-15
相关资源
最近更新 更多