如何在Java中使用switch case格式化给定的日期?

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

How can I format a given date in Java using switch case?

问题

import java.util.Scanner;

public class TugasNo4 {
    public static void main(String[] args) {
        int years, month, date, nday;
        String monthname = "";

        Scanner input = new Scanner(System.in);

        System.out.print("Year: ");
        years = input.nextInt();

        System.out.print("Month: ");
        month = input.nextInt();

        System.out.print("Date: ");
        date = input.nextInt();
        if (date <= 0) {
            System.out.println("You entered an invalid date!");
            input.close();
        }

        System.out.print("Next N days: ");
        nday = input.nextInt();

        switch (month) {
            case 1:
                monthname = "January";
                System.out.println(monthname + " has as many as 31 days");
                break;
            case 3:
                monthname = "March";
                System.out.println(monthname + " has as many as 31 days");
                break;
            case 5:
                monthname = "May";
                System.out.println(monthname + " has as many as 31 days");
                break;
            case 7:
                monthname = "July";
                System.out.println(monthname + " has as many as 31 days");
                break;
            case 8:
                monthname = "August";
                System.out.println(monthname + " has as many as 31 days");
                break;
            case 10:
                monthname = "October";
                System.out.println(monthname + " has as many as 31 days");
                break;
            case 12:
                monthname = "December";
                System.out.println(monthname + " has as many as 31 days");
                break;
            case 4:
                monthname = "April";
                System.out.println(monthname + " has as many as 30 days");
                break;
            case 6:
                monthname = "June";
                System.out.println(monthname + " has as many as 30 days");
                break;
            case 9:
                monthname = "September";
                System.out.println(monthname + " has as many as 30 days");
                break;
            case 11:
                monthname = "November";
                System.out.println(monthname + " has as many as 30 days");
                break;
            case 2:
                monthname = "February";
                if ((years % 4 == 0) && !(years % 100 == 0))
                    System.out.println(monthname + " has as many as 29 days");
                else
                    System.out.println(monthname + " has as many as 28 days");
                break;
            default:
                System.out.println("You entered an invalid month");
                break;
        }
        System.out.println("Today's date: " + monthname + " " + date + ", " + years);

        int dateTomorrow = date + 1;
        System.out.println("Tomorrow's date: " + getMonthName(month, dateTomorrow) + " " + dateTomorrow + ", " + (month == 12 ? years + 1 : years));

        int dateNdays = date + nday;
        int newMonth = month;
        int newYear = years;
        while (dateNdays > daysInMonth(newMonth, newYear)) {
            dateNdays -= daysInMonth(newMonth, newYear);
            newMonth++;
            if (newMonth > 12) {
                newMonth = 1;
                newYear++;
            }
        }
        System.out.println(nday + " days to go: " + getMonthName(newMonth, dateNdays) + " " + dateNdays + ", " + newYear);
    }

    static int daysInMonth(int month, int year) {
        switch (month) {
            case 2:
                return (year % 4 == 0) && !(year % 100 == 0) ? 29 : 28;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            default:
                return 31;
        }
    }

    static String getMonthName(int month, int day) {
        String[] monthNames = {
            "January", "February", "March", "April", "May", "June",
            "July", "August", "September", "October", "November", "December"
        };
        return monthNames[month - 1];
    }
}
英文:

I need to format a date (month, year), but I can't do it correctly.

The problem is:
Given the following data
Year: 2016
Month: 12
Date: 31
Next N days: 5

Produce the following output:
"December has as many as 31 days"
"Today date: December 31st 2016"
"Tomorrow's date: January 1, 2017"
"5 days to go: January 5, 2017".

How can I format those dates by using a switch statement (as requested by my teacher)?

import java.util.Scanner;
import javax.lang.model.util.ElementScanner6;
public class TugasNo4 {
public static void main(String[] args) {
int years, month, date, nday;
String monthname = &quot;&quot;;
Scanner input = new Scanner(System.in);
System.out.print(&quot;Tahun: &quot;);
years = input.nextInt();
System.out.print(&quot;Bulan: &quot;);
month = input.nextInt();
System.out.print(&quot;Tanggal: &quot;);
date = input.nextInt();
if(date &lt;= 0){
System.out.println(&quot;Anda memasukkan tanggal yang salah!&quot;);
input.close();
}
System.out.print(&quot;N hari kedepan: &quot;);
nday = input.nextInt();        
switch(month){
case 1:
monthname = &quot;Januari&quot;;
System.out.println(monthname+&quot; memiliki hari sebanyak 31 hari&quot;);            
break;
case 3:
monthname = &quot;Maret&quot;;
System.out.println(monthname+&quot; memiliki hari sebanyak 31 hari&quot;);            
break;
case 5:
monthname = &quot;May&quot;;
System.out.println(monthname+&quot; memiliki hari sebanyak 31 hari&quot;);            
break;
case 7:
monthname = &quot;July&quot;;
System.out.println(monthname+&quot; memiliki hari sebanyak 31 hari&quot;);            
break;
case 8:
monthname = &quot;Agustus&quot;;
System.out.println(monthname+&quot; memiliki hari sebanyak 31 hari&quot;);
break;
case 10:
monthname = &quot;Oktober&quot;;
System.out.println(monthname+&quot; memiliki hari sebanyak 31 hari&quot;);
break;
case 12:
monthname = &quot;Desember&quot;;
System.out.println(monthname+&quot; memiliki hari sebanyak 31 hari&quot;);
break;
case 4:
monthname = &quot;April&quot;;
System.out.println(monthname+&quot; memiliki hari sebanyak 30 hari&quot;);
break;
case 6:
monthname = &quot;Juni&quot;;
System.out.println(monthname+&quot; memiliki hari sebanyak 30 hari&quot;);
break;
case 9:
monthname = &quot;September&quot;;
System.out.println(monthname+&quot; memiliki hari sebanyak 30 hari&quot;);
break;
case 11:
monthname = &quot;November&quot;;
System.out.println(monthname+&quot; memiliki hari sebanyak 30 hari&quot;);
break;
case 2:
monthname = &quot;Februari&quot;;
if((years % 4 == 0) &amp;&amp; !(years % 100 == 0))
System.out.println(monthname+&quot; memiliki hari sebanyak 29 hari&quot;);     
else 
System.out.println(monthname+&quot; memiliki hari sebanyak 28 hari&quot;);       
break;            
default:
System.out.println(&quot;Anda memasukkkan bulan yang salah&quot;);
break;
}
System.out.println(&quot;Hari ini tanggal: &quot;+date+&quot; &quot;+monthname+&quot; &quot;+years);
int datebesok = date + 1;
System.out.println(&quot;Besok tanggal &quot;+datebesok+&quot; &quot;+monthname+&quot; &quot;+years);
int datenday = date + nday;
if((month == 2) &amp;&amp; (datenday &lt;= 28) &amp;&amp; (datenday &lt;= 29)){
System.out.println(nday+&quot; hari lagi tanggal: &quot;+datenday+&quot; &quot;+monthname+&quot; &quot;+years);
}
}
}

答案1

得分: 1

我建议您使用现代日期时间 API来完成这个任务。您可以从**教程:日期时间**中了解更多关于现代日期时间 API 的信息。

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int year, month, dayOfMonth, nDays;
        Scanner input = new Scanner(System.in);

        System.out.print("请输入年份:");
        year = input.nextInt();

        System.out.print("请输入月份:");
        month = input.nextInt();

        System.out.print("请输入日期:");
        dayOfMonth = input.nextInt();

        System.out.print("请输入接下来的天数:");
        nDays = input.nextInt();

        LocalDate date = LocalDate.of(year, month, dayOfMonth);
        String monthName = date.getMonth().getDisplayName(TextStyle.FULL, Locale.ENGLISH);

        System.out.println(monthName + "有" + date.getMonth().length(date.isLeapYear()) + "天");

        // 输入的日期
        System.out.println("今天的日期:" + monthName + " " + ordinal(dayOfMonth) + " " + year);

        // 其他日期的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd, uuuu", Locale.ENGLISH);

        System.out.println("明天的日期:" + date.plusDays(1).format(formatter));

        System.out.println("经过" + nDays + "天:" + date.plusDays(5).format(formatter));
    }

    static String ordinal(int num) {
        String[] suffix = { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
        int m = num % 100;
        return String.valueOf(num) + suffix[(m > 3 && m < 21) ? 0 : (m % 10)];
    }
}

一个示例运行:

请输入年份:2016
请输入月份:12
请输入日期:31
请输入接下来的天数:5
十二月有31天
今天的日期:十二月 31st 2016
明天的日期:一月 01, 2017
经过5天:一月 05, 2017

注意: 函数 ordinal 已从此回答中复制。

英文:

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

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int year, month, dayOfMonth, nDays;
Scanner input = new Scanner(System.in);
System.out.print(&quot;Enter year: &quot;);
year = input.nextInt();
System.out.print(&quot;Enter month: &quot;);
month = input.nextInt();
System.out.print(&quot;Enter day: &quot;);
dayOfMonth = input.nextInt();
System.out.print(&quot;Enter next N days: &quot;);
nDays = input.nextInt();
LocalDate date = LocalDate.of(year, month, dayOfMonth);
String monthName = date.getMonth().getDisplayName(TextStyle.FULL, Locale.ENGLISH);
System.out.println(monthName + &quot; has as many days as &quot; + date.getMonth().length(date.isLeapYear()) + &quot; days&quot;);
// Entered date
System.out.println(&quot;Today&#39;s date: &quot; + monthName + &quot; &quot; + ordinal(dayOfMonth) + &quot; &quot; + year);
// Format for other dates
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;MMMM dd, uuuu&quot;, Locale.ENGLISH);
System.out.println(&quot;Tomorrow&#39;s date: &quot; + date.plusDays(1).format(formatter));
System.out.println(&quot;After &quot; + nDays + &quot; days: &quot; + date.plusDays(5).format(formatter));
}
static String ordinal(int num) {
String[] suffix = { &quot;th&quot;, &quot;st&quot;, &quot;nd&quot;, &quot;rd&quot;, &quot;th&quot;, &quot;th&quot;, &quot;th&quot;, &quot;th&quot;, &quot;th&quot;, &quot;th&quot; };
int m = num % 100;
return String.valueOf(num) + suffix[(m &gt; 3 &amp;&amp; m &lt; 21) ? 0 : (m % 10)];
}
}

A sample run:

Enter year: 2016
Enter month: 12
Enter day: 31
Enter next N days: 5
December has as many days as 31 days
Today&#39;s date: December 31st 2016
Tomorrow&#39;s date: January 01, 2017
After 5 days: January 05, 2017

Note: The function, ordinal has been copied from this answer.

答案2

得分: 0

我相信你需要将月份数据类型更改为字符串输入,可以使用String month = input.nextLine();来获取一个字符串。

英文:

I believe you need to change your month data type and input to string input by using String month = input.nextLine(); to get a String

答案3

得分: 0

首先找到明天的日期:将月份中的日期date加1。然后检查是否大于该月的天数(您已经知道如何找到该月的天数)。如果是,我们需要进入下个月的第一天。将月份增加1,将日期设为1。接下来,我们需要检查月份是否大于一年的月份数。如果是,将年份增加1,将月份设为1。

要找到5天后的日期,或者用户输入的任何天数后的日期类似,只是稍微复杂一些。在添加适当数量的天数后,如果日期大于该月的天数,减去该数目并增加月份。以您的示例为例:如果日期为31,月份为12(十二月),添加5得到36,您会发现这大于31,因此减去31得到5。在如前所述调整月份和年份后,我们得到了次年的1月5日。但我们还没有完成。用户可能输入的天数太多,以至于超过了一月的末尾。如果用户输入了594天怎么办?因此,我们需要在循环中进行检查,重复减去该月的天数并调整月份和年份,直到我们进入一个date小于等于所在月份的天数的情况。

英文:

First to find tomorrows date: You add 1 to the day of month, date. Then check if it has become greater than the number of days in the month (you already know how to find the number of days in the month). If it has, we need to go to the first day of the following month. Increment month by 1 and set day of month to 1. Now we need to check whether month has become greater than the number of months in a year. If so, increment year and set month to 1.

To find the date after 5 days, or after any number of days that the user enters is similar, only a bit more complicated. After adding the appropriate number of days, if the date is greater than the number of days in the month, subtract that number and increase the month. Taking your example: if date is 31 and month is 12 (December), you add 5 and get 36, you see that this is greater than 31, so you subtract 31 and get 5. After adjusting month and year as before, we have got January 5 the following year. We’re not done yet. The user may enter so many days that we get past the end of January too. What if the user enters 594 days? So we need to do that check in a loop, repeatedly subtracting the number of days in the month and adjusting month and year, until we get into a situation where date is less than or equal to the number of days in the month where we have landed.

PS As others have said, for production code one would and should use java.time, the modern Java date and time API, and its LocalDate class. But as an exercise you should of course do as your teacher says, and it’s a fine exercise, you are surely learning.

huangapple
  • 本文由 发表于 2020年9月27日 13:09:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/64085020.html
匿名

发表评论

匿名网友

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

确定