如何在Java中显示日期名称?

时间:2014-06-25 08:38:30

标签: java date time

我在java的开头章节,本章介绍if和else语句和开关。我无法像星期日,星期一那样打印今天和未来的日子,而是显示像0,1这样的数字。当我使用if和else语句以供将来约会时,我今天不能改变它,反之亦然。我现在已经做到了这一点。

import java.util.Scanner;

public class Exercise03_05
{
 public static void main (String[] args)
 {
  Scanner input = new Scanner (System.in);

  System.out.print ("Enter today's day: ");
  int dayNumber = input.nextInt();

  System.out.print ("Enter the number of days elapsed since today: ");
  int daysElapsed = input.nextInt();

// Giving initial value to futureDay
  int futureDay = 0;

  if (daysElapsed < 7)
  futureDay = daysElapsed;
  else 
  futureDay = daysElapsed / 7;

  System.out.println ("Today is " + dayNumber + " and the future day is " + futureDay);
 }
}

3 个答案:

答案 0 :(得分:0)

使用年,月和日构建GregorianCalendar,然后查询它以查找当天的名称。像这样:

    String days[] ={"Thursday","Friday","Saturday","Sunday","Monday","Tuesday","Wednesday"};
    int year = 2014;
    int month = 6;
    int dayOfMonth = 25;
    Calendar myCalendar = new GregorianCalendar(year, month, dayOfMonth);
    System.out.print(days[myCalendar.get(Calendar.DAY_OF_WEEK)]);

答案 1 :(得分:0)

最简单的基本方法是使用日期名称定义一个字符串数组,并使用您已有的索引调用它们:

String days[] ={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};

而不是dayNumber,而是致电days[dayNumber]

Ex:System.out.println(days[0]);将输出Monday

答案 2 :(得分:-1)

一个数字和一天之间没有固有的翻译。您需要手动编译翻译。

由于您的章节包含switch的使用,您应该研究如何使用此构造来设置变量的名称。

你需要像

这样的东西
String dayName;
switch (<a variable) {
<a number of switch branches>
}
<a print statement that uses the dayName variable>