This question already has an answer here:
这个问题在这里已有答案:
- Java String array: is there a size of method? 11 answers
Java String数组:有一个大小的方法吗? 11个答案
This is my code:
这是我的代码:
int[] p = {1,2,3,4,5};
System.out.print("Even numbers: ");
for (int i = 0; i < p.length; i++) {
if (p[i] == 0) {
} else if (p[i] % 2 == 0) {
System.out.print(p[i] + " ");
}
}
System.out.print("\nOdd numbers: ");
for (int i = 0; i < p.length; i++) {
if (p[i] % 2 != 0) {
System.out.print(p[i] + " ");
}
}
This program prints:
该程序打印:
Even numbers: 2 4
Odd numbers: 1 3 5
Next I want to change my code to print something like this:
接下来我想改变我的代码来打印这样的东西:
Even numbers: 2
Odd numbers: 3
This would mean that I want to print the number of even and odd intigers in the array.
这意味着我想在数组中打印偶数和奇数intigers的数量。
How do I do this?
我该怎么做呢?
2 个解决方案
#1
1
just keep a counter
只是保持一个柜台
int[] p = {1,2,3,4,5};
int oddCount=0;
int evenCount=0;
System.out.print("Even numbers: ");
for (int i = 0; i < p.length; i++) {
if (p[i] == 0) {
} else if (p[i] % 2 == 0) {
System.out.print(p[i] + " ");
evenCount++;
}
}
System.out.println("Evencount"+evenCount);
System.out.print("\nOdd numbers: ");
for (int i = 0; i < p.length; i++) {
if (p[i] % 2 != 0) {
System.out.print(p[i] + " ");
oddCount++;
}
}
System.out.println("Odd count"+oddCount);
#2
0
class Test
{
public static void main(String args[])
{
int noEven=0;
int noOdd=0;
int[] p = {1,2,3,4,5};
System.out.print("Even numbers: ");
for (int i = 0; i < p.length; i++) {
if (p[i] == 0) {
} else if (p[i] % 2 == 0) {
//System.out.print(p[i] + " ");
noEven++;
}
}
System.out.println(noEven);
System.out.print("\nOdd numbers: ");
for (int i = 0; i < p.length; i++) {
if (p[i] % 2 != 0) {
//System.out.print(p[i] + " ");
noOdd++;
}
}
System.out.println(noOdd);
}
}
#1
1
just keep a counter
只是保持一个柜台
int[] p = {1,2,3,4,5};
int oddCount=0;
int evenCount=0;
System.out.print("Even numbers: ");
for (int i = 0; i < p.length; i++) {
if (p[i] == 0) {
} else if (p[i] % 2 == 0) {
System.out.print(p[i] + " ");
evenCount++;
}
}
System.out.println("Evencount"+evenCount);
System.out.print("\nOdd numbers: ");
for (int i = 0; i < p.length; i++) {
if (p[i] % 2 != 0) {
System.out.print(p[i] + " ");
oddCount++;
}
}
System.out.println("Odd count"+oddCount);
#2
0
class Test
{
public static void main(String args[])
{
int noEven=0;
int noOdd=0;
int[] p = {1,2,3,4,5};
System.out.print("Even numbers: ");
for (int i = 0; i < p.length; i++) {
if (p[i] == 0) {
} else if (p[i] % 2 == 0) {
//System.out.print(p[i] + " ");
noEven++;
}
}
System.out.println(noEven);
System.out.print("\nOdd numbers: ");
for (int i = 0; i < p.length; i++) {
if (p[i] % 2 != 0) {
//System.out.print(p[i] + " ");
noOdd++;
}
}
System.out.println(noOdd);
}
}