473,772 Members | 2,442 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Arrays -- calculating statistics

5 New Member
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...smalle st number, largest number, and array size are all correct.


Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2.  
  3. public class ListStats {
  4.  
  5.     public static Scanner kbd = new Scanner (System.in);
  6.  
  7.     public static final int MAXSIZE = 4;
  8.  
  9.     public static void main(String[] args) {
  10.  
  11.         int[] nums = new int[MAXSIZE];
  12.         int usedSize;
  13.         double median, average;
  14.         String cont;
  15.  
  16.         System.out.println("Enter a list of integers from smallest to largest (enter negative number to" +
  17.         " end list): ");
  18.  
  19.         usedSize = getNums(nums);
  20.         median = calcMedian(nums);
  21.         average = calcAverage(nums);
  22.  
  23.         System.out.println("Total numbers read: " + (usedSize));
  24.         System.out.println("Smallest number in list: " + nums[0]);
  25.         System.out.println("Largest number in list: " + nums[usedSize-1]);
  26.         System.out.println("The median is: " + median);
  27.         System.out.println("The average is: " + average);        
  28.  
  29.         do{
  30.             System.out.print("\nType a value to search for: ");
  31.             int value = kbd.nextInt();
  32.             int pos = search(nums, usedSize, value);
  33.             System.out.println("The position is: " + pos);
  34.             System.out.print("\nSearch for another integer? (Y or N)");
  35.             cont = kbd.next();
  36.         }while (cont.equalsIgnoreCase("Y"));
  37.  
  38.     }
  39.     public static int getNums(int[]nums){
  40.  
  41.         int index = 0;
  42.  
  43.         int userEntry = kbd.nextInt();
  44.         while(userEntry >= 0 && index+1 < MAXSIZE){
  45.             nums[index] = userEntry;
  46.             index++;
  47.             userEntry = kbd.nextInt();
  48.         }
  49.         if (index+1 == MAXSIZE){
  50.             nums[index] = userEntry;
  51.             index++;
  52.             System.out.println("\nMaximum size has been reached.");
  53.         }
  54.         return index;
  55.     }
  56.  
  57.     public static double calcMedian(int[]nums){
  58.  
  59.         double med;
  60.  
  61.         if (nums.length % 2 != 0)
  62.             med = nums[nums.length/2];
  63.         else {
  64.             med = ((double)nums[(nums.length/2)-1] + (double)nums[nums.length/2]) / 2;
  65.         }
  66.         return med;
  67.     }
  68.  
  69.     public static double calcAverage(int[]nums){
  70.  
  71.         double avg;
  72.         int sum = 0;
  73.  
  74.         for ( int x=0; x < nums.length; x++ ) {
  75.             sum = sum + nums[x]; }
  76.         avg = (double)sum / nums.length;
  77.         return avg;
  78.     }
  79.  
  80.     public static int search(int[]nums, int usedSize, int value){
  81.         for( int pos=0; pos < usedSize; pos++ ) {
  82.             if ( nums[pos] == value ) {
  83.                 return pos;
  84.             }
  85.         }
  86.         return -1;
  87.     }
  88. }
  89.  
  90.  
  91.  
Apr 13 '09 #1
1 3550
JosAH
11,448 Recognized Expert MVP
Your 'usedSize' variable is a local variable, i.e. your other methods know nothing about it; you should pass it to those functions as well (as an another parameter) so those functions can use that instead of the array.length value.

kind regards,

Jos
Apr 13 '09 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

12
9197
by: Dave Theese | last post by:
Hello all, I'm in a poition of trying to justify use of the STL from a performance perspective. As a starting point, can anyone cite any benchmarks comparing vectors to plain old statically-declared arrays? I'll also be looking at the other STL containers later... Also, I'd appreciate any comments anyone has on the suitability of the little program below for comparing vectors and arrays. One obvious shortcoming is that it uses...
17
14078
by: Felix | last post by:
Dear Sql Server experts: First off, I am no sql server expert :) A few months ago I put a database into a production environment. Recently, It was brought to my attention that a particular query that executed quite quickly in our dev environment was painfully slow in production. I analyzed the the plan on the production server (it looked good), and then tried quite a few tips that I'd gleaned from reading newsgroups. Nothing worked....
27
2634
by: Mike P | last post by:
I will be passing my function a two dimensional array of varying length. Within that array is one data point, and the number of times it should loop through. So, for example, I might pass this to the function: example = new Array("A",2); example = new Array("Q",4); function loopIt(example);
9
6674
by: Charles Banas | last post by:
i've got an interesting peice of code i'm maintaining, and i'd like to get some opinions and comments on it, hopefully so i can gain some sort of insight as to why this works. at the top of the function (which was translated from Fortran code), among other heinous and numerous declarations, is this bit: static float bbuff; static int bkey; static int buse;
9
1389
by: David Helgason | last post by:
I'm calling one stored procedure with a prepared statement on the server with 6 arrays of around 1200 elements each as parameters. The parameters are around 220K in total. This is taking a surprising amount of time. Thus I put a lot of logging into the application and in the stored procedure that's getting called. It seems that almost all of most of the time is spent before the stored procedure is even entered. What wakes my suspicion...
2
1968
by: Renjini | last post by:
hi everyone, i have a problem. i have been using an FFT method for 1D arrays. now i need to extend the code for 2D arrays..i thought it would be simple and i managed to implement the FFT method for every row in the array..the problem is now that i need to do the same for each of the coloumns...and the elements shud not be copied into any other arrays..because the FFT is to be applied on the original array...and the same must be given as...
17
5097
by: romixnews | last post by:
Hi, I'm facing the problem of analyzing a memory allocation dynamic and object creation dynamics of a very big C++ application with a goal of optimizing its performance and eventually also identifying memory leaks. The application in question is the Mozilla Web Browser. I also have had similar tasks before in the compiler construction area. And it is easy to come up with many more examples, where such kind of statistics can be very...
0
1712
by: cameron | last post by:
Hi everyone, I am in the process of writing my last program for my Introduction to C++ class. I have to write a program what will allow a end user to input an amount of a mortgage, from there, I have to get a monthly payment from the following choices which I have to use an array: - 7 year at 5.35% -15 year at 5.5% -30 yea at 5.75% I am currently reading about arrays, I figured I have to set a two-dimensional array, here is the code I have...
2
1469
by: Martien van Wanrooij | last post by:
I am working on some financial calculators and although I succeeded to created the required formulas I am not sure about the following.To give an example: when somebody puts a capital on the bank with a yearly interest of x % , the final capital after, say, 30 years can easily be calculated. Since I want to be able to show the capital created after every year I prefer to do it with a loop, something like for($x= 1; $x < 30; $x++){...
0
9621
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10039
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9914
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5355
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4009
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3610
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.