0

我正在尝试比较 100 条记录的列表应该有 "true" 或 false 或 null 。

我已经获取了 Array 中列表的所有值,其中包含 100 条记录,其值为例如 [0]-true、[1]-true、[2]-false、... 等等。

现在我想创建一个方法来比较值列表应该至少具有三个值中的任何一个,即 true、false 或 null。如果满足此条件,则该方法应返回 true。

如果所有值列表都是false 那么它应该返回false

但是我创建的方法总是检查第一个索引值。

这里的列表中有字符串值。有人可以帮我完成这项任务吗?谢谢

public boolean isAllRecordsAreValid (String []list) {
    boolean ret= false;   
    for (int i=0;i<list.length; i++){
        if ( list[i].equals("true")&& list[i].equals(null)&&list.equals("false")){
            return false ;
        }
    return true;
    }
    return ret;
}
4

1 回答 1

0

据我了解,您有两种情况可以涵盖三种情况。因此,如果您的数组包含的值不同于“至少一个真、假和空”或“全为假”,那么您的问题不清楚必须返回什么值。因此,您可以做的是为第三种情况引发异常(例如,数组仅包含true值或仅包含false值等)

此外,不清楚您是指字符串“null”还是 null 值。没有这些信息,很难理解如何更好地提供帮助,但我认为您可以使用此代码更好地指导自己:

public class A {

    public boolean isAllRecordsAreValid (String []list) {

        boolean hasNull = false;   
        boolean hasTrue = false;   
        boolean hasFalse = false;   
        boolean allAreFalse = true;

        for (int i=0;i<list.length; i++) {

            if( list[i] == null || list[i].equals("null") ){
                hasNull = true;
                allAreFalse = false;
            } else if( list[i].equals( "true" ) ){
                hasTrue = true;
                allAreFalse = false;
            } else if( list[i].equals( "false" ) ){
                hasFalse= true;
            }

            if( hasNull && hasTrue && hasFalse ) {
                return true;
            }

        }
        
        if( allAreFalse ){
            return false;
        }else{
            throw new UnsupportedOperationException("The array is not supported");
        }

    }

    public static void main(String[] args) {
        String[] test1 = {"true", "false", null};
        String[] test2 = {"true", "false", "null"};
        String[] test3 = {"false", "false", "false"};
        String[] test4 = {"true", "true", "true"};

        A a = new A();

        System.out.println( "test1: "+ a.isAllRecordsAreValid( test1 ) );
        System.out.println( "test2: "+ a.isAllRecordsAreValid( test2 ) );
        System.out.println( "test3: "+ a.isAllRecordsAreValid( test3 ) );
        System.out.println( "test4: "+ a.isAllRecordsAreValid( test4 ) );
    }
}
于 2021-05-20T10:59:03.313 回答