在一个要求根据日期确定日期的问题中,得到了意外的输出。

huangapple go评论80阅读模式
英文:

getting unexpected outputs in a question which asks to tell the day from date

问题

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {
    int month, day, year;

    public static boolean leap(int year) {
        if (year % 400 == 0) {
            return true;
        } else if (year % 100 == 0) {
            return false;
        } else if (year % 4 == 0) {
            return true;
        } else {
            return false;
        }
    };

    public static int year_count(int year) {
        int count = 0;
        for (int i = 2000; i < year; i++) {
            if (leap(year)) {
                count += 366;
            } else {
                count += 365;
            }
        };
        return count;
    };

    public static int month_count(int m, int y) {
        int k = m - 1;
        int[] ny = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        int[] ly = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        if (leap(y)) {
            if (k == 1) {
                return 31;
            } else {
                return ly[k] + month_count(k - 1, y);
            }
        } else {
            if (k == 1) {
                return 31;
            } else {
                return ny[k] + month_count(k - 1, y);
            }
        }
    };

    public static int total_count(int d, int m, int y) {
        return d + month_count(m, y) + year_count(y);
    }

    public static String findDay(int month, int day, int year) {
        int n = total_count(day, month, year) % 7;
        String[] days = { "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY" };
        return days[n];
    }
}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");

        int month = Integer.parseInt(firstMultipleInput[0]);
        int day = Integer.parseInt(firstMultipleInput[1]);
        int year = Integer.parseInt(firstMultipleInput[2]);

        String res = Result.findDay(month, day, year);

        bufferedWriter.write(res);
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Output is correct for:

  1. 02 13 2010 which gives SATURDAY
  2. 08 05 2015 which gives WEDNESDAY

Output is not correct for:

  1. 02 29 2004 which is giving SATURDAY but should give SUNDAY
  2. 08 05 2999 which is giving SUNDAY but should give MONDAY
  3. 04 06 2012 which is giving MONDAY but should give FRIDAY
英文:

This question is from a website and part of the code was already given by them (the solution class) asked to make a program that tells day based on date.

I have made the result class and the outputs are sometimes correct and sometimes not there is no compilation error. Can anyone please tell where the logical error lies.

ALSO CAN SOMEONE tell a better way of doing this like a bit lesser code.
Thanks in advance.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
int month,day,year;
public static boolean leap(int year){
if(year%400==0){
return true;
}
else if(year%100==0){
return false;
}else if(year%4==0){
return true;
}else{
return false;
}
};
public static int year_count(int year){
int count=0;
for(int i=2000;i&lt;year;i++){
if(leap(year)){
count += 366;
}
else{
count += 365;
}
};
return count;
};
public static int month_count(int m,int y){
int k=m-1;
int [] ny = {31,28,31,30,31,30,31,31,30,31,30,31};
int [] ly = {31,29,31,30,31,30,31,31,30,31,30,31};
if(leap(y)){
if(k==1){
return 31;
}
else{
return ly[k] + month_count(k-1,y);
}
}else{
if(k==1){
return 31;
}
else{
return ny[k] + month_count(k-1,y);
}
}
};
public static int total_count(int d,int m,int y){
return d+month_count(m,y)+year_count(y);
}
public static String findDay(int month, int day, int year) {
int n = total_count(day,month,year) % 7;
String [] days={&quot;MONDAY&quot;,&quot;TUESDAY&quot;,&quot;WEDNESDAY&quot;,&quot;THURSDAY&quot;,&quot;FRIDAY&quot;,&quot;SATURDAY&quot;,&quot;SUNDAY&quot;};
return days[n];
}
}
//no need check this below part as it was given by the browser from which the question was taken
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv(&quot;OUTPUT_PATH&quot;)));
String[] firstMultipleInput = bufferedReader.readLine().replaceAll(&quot;\\s+$&quot;, &quot;&quot;).split(&quot; &quot;);
int month = Integer.parseInt(firstMultipleInput[0]);
int day = Integer.parseInt(firstMultipleInput[1]);
int year = Integer.parseInt(firstMultipleInput[2]);
String res = Result.findDay(month, day, year);
bufferedWriter.write(res);
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}

THE OUTPUT IS CORRECT FOR :

1.02 13 2010 which gives SATURDAY

2.08 05 2015 which gives WEDNESDAY

THE OUTPUT IS NOT CORRECT FOR:

  1. 02 29 2004 which is giving SATURDAY but should give SUNDAY
  2. 08 05 2999 which is giving SUNDAY but should give MONDAY
  3. 04 06 2012 which is giving MONDAY but should give FRIDAY

答案1

得分: 5

代码中有一些错误。

错误1:

year_count 检查传入的年份是否是闰年,而不是循环中迭代的年份。更改为:

for (int i = 2000; i < year; i++) {
    if (leap(i))

错误2:

month_count 跳过了一些月份。由于 k=m-1,对 month_count 的递归调用应该使用 k,而不是 k-1。此外,它使用错误的索引来查找从错误的索引处获取的天数。更正为:

return ly[k-1] + month_count(k, y);

和:

return ny[k-1] + month_count(k, y);

错误3:

findDay 假设 2000 年 1 月 1 日是星期日。实际上是星期六。因此,星期数组应该以“FRIDAY”开头:

String[] days = {"FRIDAY", "SATURDAY", "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY"};

还有人能不能提供一种更好的方法,代码稍微少一些。

使用 java.time 包中的标准库类:

import java.time.LocalDate;
import java.time.DayOfWeek;

public static String findDay(int month, int day, int year) {
    return LocalDate.of(year, month, day).getDayOfWeek().name();
}
英文:

There are a few mistakes in the code.

Mistake 1:

year_count checks if the year passed in is a leap year, not the year you iterate over in the loop. Change to:

    for(int i=2000;i&lt;year;i++){
if(leap(i))

Mistake 2:

month_count skips over months. Since k=m-1, the recursive call to month_count should use k, not k-1. Also it uses the wrong index to look up the number of days from the wrong index. Change to:

            return ly[k-1] + month_count(k,y);

and to:

            return ny[k-1] + month_count(k,y);

Mistake 3:

findDay assumes that Jan 1 2000 was a Sunday. It was a Saturday. The array of days should therefore start with FRIDAY:

    String [] days={&quot;FRIDAY&quot;,&quot;SATURDAY&quot;,&quot;SUNDAY&quot;,&quot;MONDAY&quot;,&quot;TUESDAY&quot;,&quot;WEDNESDAY&quot;,&quot;THURSDAY&quot;};

> ALSO CAN SOMEONE tell a better way of doing this like a bit lesser code.

Use the standard library classes in the java.time package:

public static String findDay(int month, int day, int year) {
return LocalDate.of(year, month, day).getDayOfWeek().name();
}

答案2

得分: 3

我建议您使用[`java.time`日期时间API][1]来完成可以从**[教程: 日期时间][2]**中了解更多关于这个现代化日期时间API的信息

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // 测试字符串
        String[] dateStrings = { "02 13 2010", "08 05 2015", "02 29 2004", "08 05 2999", "04 06 2012" };

        // 定义格式化器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM dd uuuu");

        for (String dateString : dateStrings) {
            System.out.println(LocalDate.parse(dateString, formatter).getDayOfWeek());
        }
    }
}

**输出:**

    SATURDAY
    WEDNESDAY
    SUNDAY
    MONDAY
    FRIDAY


  [1]: https://www.oracle.com/technical-resources/articles/java/jf14-date-time.html
  [2]: https://docs.oracle.com/javase/tutorial/datetime/index.html
英文:

I suggest you do it by using the java.time date-time API. Learn more about this modern date-time API from Trail: Date Time.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Test strings
String[] dateStrings = { &quot;02 13 2010&quot;, &quot;08 05 2015&quot;, &quot;02 29 2004&quot;, &quot;08 05 2999&quot;, &quot;04 06 2012&quot; };
// Define formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;MM dd uuuu&quot;);
for (String dateString : dateStrings) {
System.out.println(LocalDate.parse(dateString, formatter).getDayOfWeek());
}
}
}

Output:

SATURDAY
WEDNESDAY
SUNDAY
MONDAY
FRIDAY

答案3

得分: 3

我不知道你的代码出了什么问题,但我可以提供一个更好的方法来完成这个任务:
在Java中有一个Calendar类(java.util.Calendar),可以用来解决这个问题:

public static String findDay(int month, int day, int year) {
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MONTH, month-1);
    cal.set(Calendar.DAY_OF_MONTH, day);
    cal.set(Calendar.YEAR, year);

    String[] day_of_week = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};

    return day_of_week[cal.get(Calendar.DAY_OF_WEEK)-1];
}
}
英文:

I don't know what your code is going wrong, but I can suggest a better way to do it:
there is a Calendar Class (java.util.Calendar) in java which can be used to solve this problem:

public static String findDay(int month, int day, int year) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, month-1);
cal.set(Calendar.DAY_OF_MONTH, day);
cal.set(Calendar.YEAR, year);
String[] day_of_week = {&quot;SUNDAY&quot;, &quot;MONDAY&quot;, &quot;TUESDAY&quot;, &quot;WEDNESDAY&quot;, &quot;THURSDAY&quot;, &quot;FRIDAY&quot;,&quot;SATURDAY&quot;};
return day_of_week[cal.get(Calendar.DAY_OF_WEEK)-1];
}
}

huangapple
  • 本文由 发表于 2020年8月23日 19:42:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63546529.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定