[英]Find and count odd numbers in a array with using an if
所以我一直在尝试在没有 if 帮助的情况下计算数组中的奇数。 那里的任何主编码器(我是新手)。
public static void main(String[] args) {
int array[] = {1,4,5,9,0,-1,5,7};
int count = 0;
for (int i = 0; i <array.length ; i++) {
if (array[i] %2 != 0){
count ++;
}
}
System.out.println("Odds " + count);
}
更好的是,甚至不需要 ;)
public static void main(String[] args) {
int array[] = { 1, 4, 5, 9, 0, -1, 5, 7 };
long count = Arrays.stream(array).filter(it -> (it & 1) == 1).count();
System.out.println("Odds " + count);
}
好了,所有你需要做的是建立在int数组到一个String
使用StringBuilder
...
然后你需要把它按偶数和几率分成两个数组! 现在你有一个偶数数组和一个赔率数组! 作为字符串! 您可以通过获取数组的长度来找到赔率的数量。 然后,您还可以将它们解析回int
或将它们保留为String
并打印它们:
int array[] = {1,4,5,9,0,-1,5,7};
StringBuilder sb = new StringBuilder();
for (int i = 0; i <array.length ; i++)
{
sb.append(array[i]);
sb.append(",");
}
String str = sb.toString();
//You can split and them parse them back into an integer! And then print them anyway!
String[] odds = str.split("\\,*\\-*\\s*[24680]*\\,");
//This is the number of odds!
System.out.println(odds.length);
for (String odd : odds) {
int oddNum = Integer.parseInt(odd);
System.out.print(oddNum + " ");
}
System.out.println();
//Or just print them!
String[] evens = str.split("\\,*\\-*\\s*[13579]*\\,");
for (String even : evens) {
System.out.print(even + " ");
}
注意:我的正则表达式不是最好的,这可以改进以更好地删除空格/空字符
附注。 没有if
语句在编写此代码时受到损害。 此外,这段代码显然不打算在真实环境中使用,我把它弄乱了正则表达式,但它做了所需的工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.