Reputation: 13
I'm having problems executing this program in which I have to enable Java to return the amount of Positive numbers in an array of integers already typed in the line of command.
public class A1Q1 {
private static int countPositive(int[] array) {
int positive = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] > 0) {
positive = positive + 1;
}
System.out.println(positive);
}
return positive;
}
public static void main(String args[]) {
int[] array = new int[]{5, 6, 7, 45, -2, -9};
int count = countPositive(array);
System.out.println(count);
}
}
Upvotes: 0
Views: 243
Reputation: 311
Java 7 or before:
private static int countPositive(int[] array) {
int positive = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] > 0) {
positive = positive + 1;
}
}
return positive;
}
Java 8 version:
private static int countPositive(int[] array) {
return (int) Arrays.stream(array).filter(number -> number > 0).count();
}
No changes in main method.
Upvotes: 0
Reputation: 59968
Your program have many problem try this code :
private static int countPositive(int[] array) {
int positive = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] > 0) { //should be greater than 0
positive++;
}
}
return positive;
}
public static void main(String args[]) {
int[] array = new int[]{5, 6, 7, 45, -2, -9};
int count = countPositive(array);
System.out.println(count);
}
First
If you are in the same class you don't need to instantiate it again
like this you do here:
public static void main(String args[]) {
A1Q1 nt = new A1Q1();
Second
You should use the same name of method in your loop:
//-----------------------------------this name--
private static int countPositive(int[] array) {
for (int i = 0; i < array.length; i++) {
You can start java here:
And about array :
Upvotes: 2