简体   繁体   English

如何查找多个年份而不只是一个年份的复活节日期?

[英]How to find easter dates for multiple years rather than just one?

So far i have a code that calculates the date that Easter falls on once you input a year. 到目前为止,我有一个代码可以计算出您每年输入一次复活节的日期。 I need to change it so that it gives you multiple dates for multiple years (you input 2 years instead and it gives everything in between). 我需要对其进行更改,以便为您提供多年的多个日期(您输入2年而不是介于两者之间的所有日期)。 Hope that makes sense! 希望有道理!

I'm not sure what i'm meant to do here. 我不确定我要在这里做什么。 We've learnt forloops (note: we are just learning java) so I tried putting a forloop for the code but came up short because im not sure how that would work. 我们已经学习了forloops(注意:我们只是在学习Java),所以我尝试为代码放一个forloop,但由于我不确定这样做是如何进行的,所以简短了。

import java.util.Scanner;

public static void main(String[] args) {
    System.out.print("Please enter a year to calculate Easter Sunday\n>");
    Scanner sc = new Scanner(System.in);//imports java.util.Scanner to the library
    int aNumber = sc.nextInt();//saves next inputted number as "aNumber"

    while (aNumber <=0){//while statement to make sure inputted year is positive
        System.out.println("Please enter a postive year: ");
        aNumber = sc.nextInt();

    }

    int a = aNumber % 19,
        b = aNumber / 100,
        c = aNumber % 100,
        d = b / 4,
        e = b % 4,
        g = (8 * b + 13) / 25,
        h = (19 * a + b - d - g + 15) % 30,
        j = c / 4,
        k = c % 4,
        m = (a + 11 * h) / 319,
        r = (2 * e + 2 * j - k - h + m + 32) % 7,
        month = (h - m + r + 90) / 25, //determines month as a number
        date = (h - m + r + month + 19) % 32;//determines date

    String test;
    switch(month)//switch case to convert "month" to a string 
    {
        case 1:
            test = "January ";
            break;
        case 2:
            test = "February ";
            break;
        case 3:
            test = "March ";
            break;
        case 4:
            test = "April ";
            break;
        case 5:
            test = "May ";
            break;
        case 6:
            test = "June ";
            break;
        case 7:
            test = "July ";
            break;
        case 8:
            test = "August ";
            break;
        case 9:
            test = "September ";
            break;
        case 10:
            test = "October ";
            break;
        case 11:
            test = "November ";
            break;
        case 12:
            test = "December ";
            break;
        default:
            test = "error";
    }
    System.out.println("In " + aNumber + ", Easter Sunday will be on " + test + "" + date  + ".");//displays year,date and month of Easter Sunday
}

I meant to get multiple dates for every year between the two years you input. 我的意思是要在输入的两年之间每年获得多个日期。

Ok, provided that your code calculates Easter correctly, aim for something like this: 好的,只要您的代码能够正确计算复活节,就可以实现以下目标:

static String printEasterFor(int aNumber) {
        int a = aNumber % 19,
                b = aNumber / 100,
                c = aNumber % 100,
                d = b / 4,
                e = b % 4,
                g = (8 * b + 13) / 25,
                h = (19 * a + b - d - g + 15) % 30,
                j = c / 4,
                k = c % 4,
                m = (a + 11 * h) / 319,
                r = (2 * e + 2 * j - k - h + m + 32) % 7,
                month = (h - m + r + 90) / 25, //determines month as a number
                date = (h - m + r + month + 19) % 32;//determines date

        String test;
        switch(month)//switch case to convert "month" to a string
        {
            case 1:
                test = "January ";
                break;
            case 2:
                test = "February ";
                break;
            case 3:
                test = "March ";
                break;
            case 4:
                test = "April ";
                break;
            case 5:
                test = "May ";
                break;
            case 6:
                test = "June ";
                break;
            case 7:
                test = "July ";
                break;
            case 8:
                test = "August ";
                break;
            case 9:
                test = "September ";
                break;
            case 10:
                test = "October ";
                break;
            case 11:
                test = "November ";
                break;
            case 12:
                test = "December ";
                break;
            default:
                test = "error";
        }

        return "In " + aNumber + ", Easter Sunday will be on " + test + "" + date  + ".";//displays year,date and month of Easter Sunday
    }


    static List<String> showEasterBetween(int start, int end) {
        List<String> result = new ArrayList<>();
        IntStream.range(start, end).forEach(year -> result.add(printEasterFor(year)));

        return result;
    }

Then you call this like: 然后,您可以这样称呼:

public static void main(String[] args) {
    int startYear = 2005;
    int endYear = 2025;
    List<String> easters = showEasterBetween(startYear, endYear);
}

As an improvement, your method printEasterFor could return a LocalDate object instead of printing a String, but I hope that you get my idea. 作为改进,您的方法printEasterFor可以返回LocalDate对象,而不是打印String,但是我希望您能理解我的想法。

java.time java.time

The Answer by mate00 seems correct. mate00答案似乎正确。 As mentioned there, you should be using the java.time types. 如此处所述,您应该使用java.time类型。 Let's take the code shown in that other Answer, and make it more spiffy with the modern date-time classes. 让我们采用其他答案中所示的代码,并使其与现代的日期时间类更加完美。 We also change some names for clarity. 为了清楚起见,我们还更改了一些名称。

We have a Year class. 我们有一Year Using that Year type as the argument to your methods makes your code more self-documenting. 使用Year类型作为方法的参数可以使代码更具自记录性。

Year year = Year.of( 2019 ) ; 

We have LocalDate to represent a date-only value, without time-of-day and without time zone. 我们有LocalDate来表示仅日期的值,没有日期和时区。

LocalDate localDate = LocalDate.of( 2019 , Month.JANUARY , 23 ) ;

And we have the Month enum, predefining an object for each month of a year. 我们有Month枚举,为一年中的每个月预定义一个对象。 Using the Month enum, we can collapse your long switch statement to one or two lines. 使用“ Month枚举,我们可以将您的long switch语句折叠为一两行。 The Month.values() method generates an array of all the objects pre-instantiated by the enum. Month.values()方法生成一个由枚举预先实例化的所有对象的数组。 We can pick a month from that array by number. 我们可以按数字从该数组中选择一个月。 But we must use annoying zero-based index counting. 但是我们必须使用恼人的从零开始的索引计数。 Subtract one from 1-12 to get 0-11. 从1-12减去1得到0-11。

Month month = Month.values()[ 1-1 ];  // Get `Month.JANUARY` object for month number 1 (index number 0). 

Example code 范例程式码

Here is an entire example class, Easter with a pair of methods overloading of (passing either a single year or a pair of years). 下面是一个整个示例类, Easter有一对重载方法of (通过一个单一的一年或双年)。 Perhaps forYear and forYears might be better method names, given the established java.time naming conventions . 给定已建立的java.time命名约定 ,也许forYearforYears可能是更好的方法名称。 Ideal name would be for but that is a reserved keyword for the for loop. 理想名称是for但这是for循环的保留关键字。

Beware: I have not tested the results of this code. 注意:我尚未测试此代码的结果。 Use at your own risk. 使用风险自负。

package work.basil.example;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import java.time.*;

public class Easter
{

    static LocalDate of ( Year year )
    {
        int yearNumber = year.getValue(); // Convert from object to simple integer.
        int a = yearNumber % 19,
                b = yearNumber / 100,
                c = yearNumber % 100,
                d = b / 4,
                e = b % 4,
                g = ( 8 * b + 13 ) / 25,
                h = ( 19 * a + b - d - g + 15 ) % 30,
                j = c / 4,
                k = c % 4,
                m = ( a + 11 * h ) / 319,
                r = ( 2 * e + 2 * j - k - h + m + 32 ) % 7,
                monthNumber = ( h - m + r + 90 ) / 25, //determines month as a number
                dayOfMonth = ( h - m + r + monthNumber + 19 ) % 32;//determines date

        int monthIndex = ( monthNumber - 1 ); // Convert from ordinal number to index number, zero-based for accessing an array in Java.
        Month month = Month.values()[ monthIndex ];  // Get the `Month` enum object for this month index. Throws an exception if the month index is out of range of 0-11.

        LocalDate easter = LocalDate.of( yearNumber , month , dayOfMonth );
        return easter;
    }

    static List < LocalDate > of ( Year start , Year stop )
    {
        Objects.requireNonNull( start );
        Objects.requireNonNull( stop );
        if ( stop.isBefore( start ) )  // Verify the stop year is not before the start year. Defensive programming. 
        {
            throw new IllegalArgumentException( "The stop year cannot be before the start year. Message # 296232f7-0c6e-49c2-a462-851aa0b30352." );
        }
        List < LocalDate > easters = new ArrayList <>();
        Year year = start;
        while ( year.isBefore( stop ) )
        {
            LocalDate easter = Easter.of( year );  // Determine the date of Easter for this particular year.
            easters.add( easter );
            // Prepare for next loop.
            year = year.plusYears( 1L );  // Increment to the next year in succession.
        }

        return easters;
    }

    public static void main ( String[] args )
    {
        List < LocalDate > easters = Easter.of( Year.of( 2005 ) , Year.of( 2010 ) );
        System.out.println( "easters.toString(): " + easters );
    }
}

When run. 运行时。

easters.toString(): [2005-03-27, 2006-04-16, 2007-04-08, 2008-03-23, 2009-04-12] Easters.toString():[2005-03-27、2006-04-16、2007-04-08、2008-03-23、2009-04-12]

We don't really need the Month enum in this particular routine. 在此特定例程中,我们实际上并不需要Month枚举。 We could just pass the monthNumber integer to the factory method LocalDate::of . 我们可以将monthNumber整数传递给工厂方法LocalDate::of

LocalDate easter = LocalDate.of( yearNumber , monthNumber , dayOfMonth );

Strings 弦乐

To generate strings representing these LocalDate objects' value, use the DateTimeFormatter class, especially its ofLocalizedDate method. 若要生成表示这些LocalDate对象值的字符串,请使用DateTimeFormatter类,尤其是其ofLocalizedDate方法。 Search Stack Overflow for more info, as this has been covered many many times already. 搜索堆栈溢出以获取更多信息,因为已经讨论了很多次。

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH) ;  // Or `Locale.US` etc.
String output = localDate.format( f ) ;

dimanche 27 mars 2005 dimanche 2005年3月27日

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

相关问题 如何在一行而不是多个中更新? - How to update in one line rather than multiple? 我如何在SQLite中基于3个值而不只是一个值返回一行? (已完成1个代码) - How do I within SQLite, return a row based on 3 values rather than just one? (Already done code for 1) 如何计算两个日期之间的差值是否大于20年? - How to calculate if the difference between two dates is greater than 20 years? 查找日期列表中的所有年份 - Find all the years in a list of dates 如何找到两个日期之间的年数? - How can I find the number of years between two dates? Java - 如何在我的程序中显示我的每个成绩的字母成绩,而不仅仅是我的最后一个成绩? - Java - How can I display a letter grade for each of my grades in my program rather than just my last one? 如何从文件目录而不是仅从1个文件中读取Java - How to read from a directory of files rather than just 1 file Java 多次初始化一个变量而不是重新分配一个变量是否效率低下? - Is it inefficient to initialize a variable multiple times rather than reassigning one? RecyclerView 只显示一张图片而不是多张图片 - RecyclerView only shows one image rather than multiple JavaFX需要多个ImageView节点而不是一个引用? - JavaFX requires multiple ImageView nodes rather than a reference to one?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM