从键盘中选择数组中的元素

时间:2015-11-18 15:12:56

标签: java arrays

所以我必须有array一周中的几天,然后让用户从键盘输入一个数字,然后显示该数字匹配的日期。即5周五将返回。 我遇到的问题是将用户输入告诉它打印出哪个元素。我有一种感觉,它类似于我昨天交换的问题,但无法看到如何让它工作,因为那个人有移动元素的临时位置。这是我到目前为止所拥有的:

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

      String[] days = new String[] {"Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday", "Sunday"}; 
      int number, i=0;

      System.out.print ("Enter the number of the day you want: ");
      number = keyboardIn.nextInt();
      for (i= 0; i < days.length;)
      {
       if (number<= days.length)
       {
            System.out.print (days[i]);
       }
      }
   }
}

1 个答案:

答案 0 :(得分:1)

获得索引后,您可以使用days[index]获取星期几。像这样:

Scanner keyboardIn = new Scanner(System.in);
String[] days = new String[] {"Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday", "Sunday"}; 

System.out.print ("Enter the number of the day you want: ");
int number = keyboardIn.nextInt()-1;
if (number<days.length && number>=0){
    System.out.println(days[number]);
}else{
    System.out.println("Invalid number of day of the week");
}

我减去1,因为数组从0开始。希望这有帮助!