有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在比较数据后得到错误的结果

我编写以下代码,读取一行,将它们转换为整数,并计算一行中的偶数、奇数和零位数

但问题是,每当我输入零,它都会计算count,甚至在我的代码中,而不是countZero

我的代码怎么了
我在计算代码中的偶数和奇数时没有任何问题,它只是零

    Scanner stdin = new Scanner(System.in);
    String str = "";
    int countOdd = 0, countEven = 0, countZero = 0;

    str = stdin.nextLine();
    char[] breakDown = str.toCharArray();

    Integer convertInt;


    for (int i = 0; i < breakDown.length; i++)  {
        convertInt = new Integer(breakDown[i]);

        if (convertInt % 2 == 1)
            countOdd++;  

        if (convertInt % 2 == 0 && convertInt != 0)
            countEven++;

        if (convertInt == 0)
            countZero++;  }

共 (1) 个答案

  1. # 1 楼答案

    将字符'0'强制转换为整数时,它将变为48,而不是0。表达式breakDown[i]的类型为char,但当您将其传递给Integer构造函数时,它将被转换为int

    您只需摆脱对Integer的转换,并将其写入循环中即可

        if (breakDown[i] % 2 == 1) {
            countOdd++;  
        }
    
        if (breakDown[i] % 2 == 0 && breakDown[i] != '0') {
            countEven++;
        }
    
        if (breakDown[i] == '0') {
            countZero++;
        }