对于循环未正确运行

时间:2015-07-14 20:00:16

标签: java arrays for-loop integer

当我执行此代码时,输​​出为" 140"这是" 28 * 5"但它应该是" 150"这是" 28 + 31 + 30 + 31 + 30"它应该计算2个月之间的天数" feb"并且" 7月" ...所以这意味着for循环没有正常工作或者什么?那为什么呢 !你能在这帮我吗? PS:我试图将循环中的j ++更改为j + 1,但Android Studio表示"这不是声明"

int[] pair = {1,3,5,7,8,10,12};
int[] impair = {4,6,9,11};
int x=0;
int j;
int year=2015;
int mm=2;
int month=7;
String msg="";
if (month>mm) {
    for (j = mm; j<month; j++){
        if (Arrays.asList(impair).contains(j)){
            x = 31 + x;
        }else if(Arrays.asList(pair).contains(j)){
            x = 30 + x;
        }else{
            if (year%4==0) {
                x= 29 + x;
            }else{
                x= 28 + x;
            }
        }
    }
    System.output.println(x);
}

3 个答案:

答案 0 :(得分:8)

您正在尝试通过调用int[]List<Integer>转换为Arrays.asList。但这导致单个元素List<int[]>(原始int[]),其中不包含j的任何值。原因在Arrays.asList() not working as it should?中给出 - 它是一个泛型方法,type参数必须是引用类型。 int[]是引用类型(与所有数组一样),但int不是。

这就是测试全部失败并重复选择添加28的原因。

将声明的pairimpair类型从int[]更改为Integer[],以便Arrays.asList将类型推断为Integer(参考类型)正确。然后contains方法将按预期工作。通过此更改,我得到150

答案 1 :(得分:1)

这是因为asList()需要一个类对象,它是一个集合和Iterable。您可以通过以下方式修改代码: -

Integer[] pair = {1,3,5,7,8,10,12};
Integer[] impair = {4,6,9,11};
int x=0;
int j;
int year=2015;
int mm=2;
int month=7;
String msg="";
if (month>mm) {
    for (j = mm; j<month; j++){
        if (Arrays.asList(impair).contains(new Integer(j))){
            x = 31 + x;
        }else if(Arrays.asList(pair).contains(new Integer(j))){
            x = 30 + x;
        }else{
            if (year%4==0) {
                x= 29 + x;
            }else{
                x= 28 + x;
            }
        }
    }
    System.output.println(x);
}

这应该会给你正确的输出。

答案 2 :(得分:0)

这是因为你的循环永远不会进入前两个如果块不是aslist(数组).contains(element)的工作方式

Java, Simplified check if int array contains int

Checking whether an element exist in an array

相关问题