2013-02-02 50 views
0

我無法從字符串數組中檢索值。如何從main()訪問字符串數組的元素

我需要輸出星期幾的名稱..即星期天的數字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); 
    } 
} 

回答

3

實際訪問數組:

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

%7是確保每天(如10)不會導致越界異常。然而,這並不是最佳的,它假定星期一是第0天,但是這個想法就在那裏。

+0

不需要再次使用'futureDay%7'。 –

+0

@LuiggiMendoza對! –

+0

我很高興知道我有點親密。我確實嘗試了代碼,並且當我使用textpad編譯器時,它說錯誤了一個非靜態變量dayStrings無法從靜態上下文中引用,然後顯示System.out.print – Lish