[英]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 Length
, setting the flag
和breaking 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.