I had a question in my exam. At first it was pretty easy. Let me explain the question:
Make the User Specify how many integers wants to put (Array)
Numbers should be between -1500 to 1500
- (Tricky): Create a method that calculates the percentage of the numbers put, what percentage were 0, positive, negative. (All this should be in ONE method, no return to string, string buffer, the return result should be a double value)
I think I did it right, but when I tested it in real time, the problem that I run is that it returns the values 0.0, 0.0, 0.0 ... Or it returns the correct percentage only if the values fall within the same condition (eg. all zero).
Here is my code: (I hope you can make sense out of it). I'm just curious, I don't know how to solve it. I have also tried it with a static method, I run into the same problem.
import java.util.Scanner;
public class nPNZ {
public int [] number;
public nPNZ (int [] n){
number = n;
}
public double [] allCalcs(){
int countPos = 0; int countNeg = 0; int countZero = 0;
for (int i = 0; i < number.length; i++) {
if (number[i] == 0) {
countZero++;
}else if (number[i] > 0){
countPos++;
}else{
countNeg++;
}
}
//0 = 0 ; 1 = positive ; 2 = negative
double total [] = new double [3];
total[0] = (countZero/number.length)*100;
total[1] = (countPos/number.length)*100;
total[2] = (countNeg/number.length)*100;
return total;
}
public static void main (String args[]){
//min 20 number, -1500 to 1500
Scanner input = new Scanner (System.in);
final int MIN_SIZE = 5;
int size = 0;
while(size < MIN_SIZE){
System.out.println("Specify the size of the array: ");
size = input.nextInt();
while(size<MIN_SIZE){
System.out.println("Size should be greater than: " + MIN_SIZE);
size = input.nextInt();
}
}
input.nextLine();
int num [] = new int [size];
for (int i = 0; i < num.length; i++) {
System.out.println("Write number " + (i+1) + " : ");
num[i] = input.nextInt();
while(num[i] < -1500 || num[i] > 1500) {
System.out.println("The number should within the range of -1500 and 1500");
num[i] = input.nextInt();
}
}
nPNZ n = new nPNZ (num);
System.out.println("Percentage of zero numbers is: " + n.allCalcs()[0] );
System.out.println("Percentage of positive numbers is: " + n.allCalcs()[1] );
System.out.println("Percentage of negative numbers is: " + n.allCalcs()[2]);
}
}