我只想添加和打印“阵列”列表中的6个项目

时间:2019-05-04 08:55:33

标签: java

如果今天是星期一,则其数目为2。我需要在接下来的5个工作日中添加不包括星期日(假日)的数组。 我是编码新手,正在学习9th Standard。请帮我编码。谢谢!

 public class WeekView {
 public static void main(String args[]) {
     List<Integer> daysList = new ArrayList<>();
     int m = 6, dayOfWeek = 6;
     for (int i = 1; i <= m; i++) {
         if (dayOfWeek == 1) {
             daysList.add(dayOfWeek);
             dayOfWeek++;
         } else if (dayOfWeek == 2) {
             daysList.add(dayOfWeek);
             dayOfWeek++;
         } else if (dayOfWeek == 3) {
             daysList.add(dayOfWeek);
             dayOfWeek++;
         } else if (dayOfWeek == 4) {
             daysList.add(dayOfWeek);
             dayOfWeek++;
         } else if (dayOfWeek == 5) {
             daysList.add(dayOfWeek);
             dayOfWeek++;
         } else if (dayOfWeek == 6) {
             daysList.add(dayOfWeek);
             for (int j = 1; j < dayOfWeek; j++) {
                 daysList.add(j);
             }
         }
     }
     System.out.println("Day Num :" + daysList);
 } }

我的当前输出是

Day Num :[6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5]

但是我需要下面给出的输出

  6,1,2,3,4,5

2 个答案:

答案 0 :(得分:3)

List<Integer> daysList = new ArrayList<>();
int day = 6;

for (int i = 0; i < 6; i++) {
    daysList.add(day);
    day++;
    if(day > 6) day = 1;
}

System.out.println("Day Num :" + daysList);

位置:

  • i迭代工作日数
  • daysList.add(day)将当天添加到列表中
  • days++,在每次循环迭代时转到第二天
  • if(day > 6) day = 1如果day到达星期日则返回星期一

答案 1 :(得分:0)

在递增时不必添加到day,可以使用模数运算符删除if检查。喜欢,

int day = 6;
List<Integer> daysList = new ArrayList<>();
for (int i = 0; i < 6; i++) {
    daysList.add(1 + ((day + i - 1) % 6));
}
System.out.println("Day Num :" + daysList);

或在Java 8+中使用IntStream生成类似值

int day = 6;
List<Integer> daysList = IntStream.range(0, 6).map(i -> 1 + ((day + i - 1) % 6)).boxed()
        .collect(Collectors.toList());
System.out.println("Day Num :" + daysList);