繁体   English   中英

java中未知长度数组的条件

[英]condition on an unknown length array in java

我有一个长度为n的char数组,我不知道该值。 我需要编写一个条件来检查数组中的所有元素是否都等于给定char'a 'a'一一对应。

例如,在n = 4的情况下,我通过执行以下操作将数组转换为字符串:

String str = new String(myArray); 

然后我做我的情况,如:

if (str.equals("aaaa")) {} 

但我的问题是n的值未知。 我试着做:

for (int i = 0; i < n; i++) { 
    if (myArray[i].equals('a')) {
        ??
    }
}

但我不知道该怎么做 在if之后,因为我需要等待for循环完成,因为我希望数组中的所有元素都等于'a'

检查所有项目的过程通常如下:

  • 检查单个项目
  • 如果符合条件,请继续
  • 否则,声明匹配失败,然后结束循环
  • 如果循环结束但未声明匹配失败,则说明匹配成功

就Java而言,声明匹配不成功可能意味着将boolean变量设置为false

boolean successfulMatch = true;
for (int i = 0; i <  myArray.length ; i++) { 
//                   ^^^^^^^^^^^^^^
//             Note how we check array length
    if (myArray[i] != 'a') {
    //             ^^
    //        Note != here
        successfulMatch = false;
        break;
    }
}
if (successfulMatch) {
    ...
}

在Java-8中,您可以使用Stream#allMatch做到这Stream#allMatch 它将减少仪式代码。 您不必担心Array Lengthsetting the flagbreaking the loop

    String[] strs = {"a","a","a"};
    boolean isAllEqual = Arrays.stream(strs).allMatch(e->e.equals("a"));
    System.out.println(isAllEqual);

关于什么:

boolean matched = true;
for(int i = 0, n=myArray.length; i<n; i++){
    if(!myArray[i].equals("a")){
         matched = false;
    }
}

然后,您要做的就是检查匹配的布尔值。

您可以简单地使用正则表达式。 例如:

    String s = "aaaaaaaa";
    if(s.matches("[a]*"))
        System.out.println("s only contains a");
    else if(s.matches("[A]*"))
        System.out.println("s only contains A");
    else if(s.matches("[aA]*"))
        System.out.println("s only contains A and a");
    else
        System.out.println("s not match a*");

尝试这个

private static  void n(){

    char[] n = {'a', 'b'};

    String[] myArray = {"a", "a", "a"};

    for(char c : n){
        int i = 0;
        int j = 0;
        for(String s : myArray){
            if((s.equals(String.valueOf(c)))){
                i++;
            }

            if(++j == n.length){

                System.out.println(i + "->" + n.length);

                if(n.length == i){
                    System.out.println("All the elemntes in your array are the same to char array");
                }else{
                    System.out.println("Not the same");
                }
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM