My code runs fine for the most part...the only time it fails is when I type in a negative to end the array. I don't want the negative number to be included in the array and I thought that is what the while loop in the getNums method does. However, it is including this negative number when calculating the avg and it is doing something weird to the median. When the array end itself because the max size has been reached everything works fine. Can anyone help me fix this so that when I use type in a negative number it closes the array and then calculates the stats? I am only having a problem with the average and median...smallest number, largest number, and array size are all correct.
-
import java.util.*;
-
-
public class ListStats {
-
-
public static Scanner kbd = new Scanner (System.in);
-
-
public static final int MAXSIZE = 4;
-
-
public static void main(String[] args) {
-
-
int[] nums = new int[MAXSIZE];
-
int usedSize;
-
double median, average;
-
String cont;
-
-
System.out.println("Enter a list of integers from smallest to largest (enter negative number to" +
-
" end list): ");
-
-
usedSize = getNums(nums);
-
median = calcMedian(nums);
-
average = calcAverage(nums);
-
-
System.out.println("Total numbers read: " + (usedSize));
-
System.out.println("Smallest number in list: " + nums[0]);
-
System.out.println("Largest number in list: " + nums[usedSize-1]);
-
System.out.println("The median is: " + median);
-
System.out.println("The average is: " + average);
-
-
do{
-
System.out.print("\nType a value to search for: ");
-
int value = kbd.nextInt();
-
int pos = search(nums, usedSize, value);
-
System.out.println("The position is: " + pos);
-
System.out.print("\nSearch for another integer? (Y or N)");
-
cont = kbd.next();
-
}while (cont.equalsIgnoreCase("Y"));
-
-
}
-
public static int getNums(int[]nums){
-
-
int index = 0;
-
-
int userEntry = kbd.nextInt();
-
while(userEntry >= 0 && index+1 < MAXSIZE){
-
nums[index] = userEntry;
-
index++;
-
userEntry = kbd.nextInt();
-
}
-
if (index+1 == MAXSIZE){
-
nums[index] = userEntry;
-
index++;
-
System.out.println("\nMaximum size has been reached.");
-
}
-
return index;
-
}
-
-
public static double calcMedian(int[]nums){
-
-
double med;
-
-
if (nums.length % 2 != 0)
-
med = nums[nums.length/2];
-
else {
-
med = ((double)nums[(nums.length/2)-1] + (double)nums[nums.length/2]) / 2;
-
}
-
return med;
-
}
-
-
public static double calcAverage(int[]nums){
-
-
double avg;
-
int sum = 0;
-
-
for ( int x=0; x < nums.length; x++ ) {
-
sum = sum + nums[x]; }
-
avg = (double)sum / nums.length;
-
return avg;
-
}
-
-
public static int search(int[]nums, int usedSize, int value){
-
for( int pos=0; pos < usedSize; pos++ ) {
-
if ( nums[pos] == value ) {
-
return pos;
-
}
-
}
-
return -1;
-
}
-
}
-
-
-