有 Java 编程相关的问题?

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

if语句如何检查java中是否存在表达式中的下一个或最后一个值

您好,我正在研究的是如何检查一个数字,例如10,然后查看下一个数字,即11和10,9之前的数字,然后取消这些数字并返回false

public static boolean continue_sequence(int x, int y){

    if(x >= 0 && y == -1 ){
        return false;
    }
    // above is separate check that works below is the one I am trying to fix
    else if(x >= 0 && y += 1 || y -= 1){
        return false;
    }
    else{
        return true;    
    }
}

以下是冗余案例的输出情况
U U Testing combination:21 U Ui Testing combination:22 U U2 Testing combination:23

这些都是冗余的,可以用一个字母替换。例如,组合23可以替换为在这些测试之前已经测试过的单个Ui,因为序列长度随着时间的推移而变长,因为有18个不同的实例(如U R L B’B2等)


共 (4) 个答案

  1. # 1 楼答案

    你可以做到的

    if((x+1 == y) || (x-1 == y)) // x and y are sequential numbers.
        return false;
    else // something else.
    

    所以,如果你把9,10作为x,y传递,那么这个陈述将是错误的

    我希望这对你有帮助

  2. # 2 楼答案

    public static boolean continue_sequence(int x, int y){
    
        if(x >= 0 && y == -1 ){
            return false;
        }
        // This if statement checks if x greater than 0 which our base condition,
        // second part "((x+1) == y || (x-1) == y)" checks x is sequential to the y    
        else if(x >= 0 && ((x+1) == y || (x-1) == y))
            return false;
        else 
            return true;
    

    }

  3. # 3 楼答案

        else if(x >= 0 && ( y += 1 || y -= 1))
    

    试试这个

  4. # 4 楼答案

    你可以简单地返回数学。abs(x-y)==1

    public static boolean continue_sequence(int x, int y){
    
            if(x >= 0 && y == -1 ){
                return false;
            }
    
            // above is separate check that works below is the one I am trying to fix
            return Math.abs(x-y) == 1;
        }