0

我很难从字符串数组中检索值。

我需要让它输出星期几的名称.. 即数字 0 的星期日。我的代码非常适合输出数字,但我无法从我的日期名称数组中提取它。

import java.util.Scanner;

public class FutureDateJava {
    String[] dayStrings = { "Sunday", "Monday", "Tuesday", 
                            "Wednesday", "Thursday", "Friday", 
                            "Saturday" };

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

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

        System.out.println("Enter a day in the future ");
        int future = input.nextInt();

        int futureDay = (today + future) % 7;

        System.out.print("Today is " + today + 
            " and the future day is " + futureDay);
    }
}
4

1 回答 1

3

实际访问数组:

System.out.print("Today is " + dayStrings [today % 7] + " and the future day is " + dayStrings [futureDay]);

%7是为了确保一天(例如 10 天)不会导致越界异常。然而,这并不完全是最优的,它假设星期一是第 0 天,但想法就在那里。

于 2013-02-02T23:59:52.327 回答