ArrayOutOfBoundsException Error? - java

I have to create classes to be implemented with the main class someone else has and for some reason I am not getting the right outputs, I'm not sure where this error is coming from.
Expected Output:
Median = 44.5
Mean = 49.300
SD = 30.581
public class StatPackage {
int count;
double [] scores;
StatPackage() {
count = 0;
scores = new double[500];
}
public void insert (double value) {
if (count < 500){
scores[count] = value;
++ count;
}
}
public double Mean () {
double sum = 0;
//For loop for calculating average or mean
for(int i = 0; i < count; i++){
sum += (scores[i]);
}
double average = sum/count;
return average;
}
public double Median() {
int min;
int tmp;
int size;
for (int i = 0; i < count; i ++)
{
min = i;
for (int pos = i + 1; pos < count; pos ++)
if (scores [pos] < scores [min])
min = pos;
tmp = (int)scores [min];
scores [min] = scores [i];
scores [i] = tmp;
}
double median = 0;
if (count % 2 == 0){
median = (scores[scores.length/2-1] + scores[scores.length/2])/2;
}
else {
median = (scores[((scores.length/2))]);
}
return median;
}
public double Variance () {
double variance = 0;
double sum = 0;
//For loop for getting the variance
for(int i = 0; i < count; i++){
sum += scores[i];
variance += scores[i] * scores[i];
}
double varianceFinal = ((variance/count)-(sum*sum)/(count*count));
return (varianceFinal);
}
public double StdDev (double variance) {
double sum = 0;
for(int i = 0; i < count; i++){
sum += scores[i];
variance += scores[i] * scores[i];
}
double varianceFinal = ((variance/count)-(sum*sum)/(count*count));
return Math.sqrt(varianceFinal);
}

You have a problem in your Median() method. Try changing
if (count % 2 == 0){
median = (scores[scores.length/2-1] + scores[scores.length/2])/2;
}
else {
median = scores[scores.length/2];
}
to
if (count % 2 == 0)
median = (scores[count/2] + scores[count/2 - 1])/2;
else
median = scores[count/2];
Because you have a fixed-size array with 500 elements, the code you have will return the mean value of the items at position 249 and 250, which will be 0 if you have less than 251 values in your array.

In a fit of charity/insanity, I quickly wrote a driver program to try to test this thing.
public static void main(String[] args)
{
StatsPackage sp = new StatsPackage();
for (int i = 0; i < 101; ++i) {
sp.insert(i);
}
System.out.println("count: " + sp.count);
System.out.println("mean: " + sp.Mean());
System.out.println("median: " + sp.Median());
System.out.println("variance: " + sp.Variance());
}
Beyond the fact the median doesn't compute the right values (and #BadCash may have the solution for that problem), there is no ArrayOutOfBounds thrown.
EDIT: making the update as #BadCash suggested to the Median method seems to resolve the median not giving the correct answer.

Related

How to store a value that comes from a for

Hi Im new to Java Im trying to make a counter. What Id like to do is calculate the numbers from 1 to x, for example if x is 5, calculate 1 + 2 + 3 + 4 + 5.
This is what I wrote, but I get 6 as output instead of 15.
public class Counter {
public int count (int x){
int contatore = 0;
int sum = 0;
for (int i = 0; i <= x; i++) {
sum = i;
System.out.println(i);
}
System.out.println(sum);
return sum;
}
}
You need to add i to the sum in each iteration of the loop:
public int count (int x) {
int contatore = 0;
int sum = 0;
for (int i = 0; i <= x; i++) {
sum += i;
System.out.println(i);
}
System.out.println(sum);
return sum;
}
You are assigning the loop variable to the sum - you need to add it to the sum
public int count (int x){
int sum = 0;
for (int i = 0; i <= x; i++) {
sum = sum + i;
}
return sum;
}
As others have noted, you can use the following shorthand notation for addition with assignment.
sum += i; // equivalent to sum = sum + i;

How do I return the sum of an array, with this code to start it off?

So this is what I have:
public static void Positive () {
int limit = 50;
for(int i=1; i <= limit; i++){
System.out.print(i + ", ");
}
}
That prints out all numbers 1-50 with a loop
How do I return the sum of this using a loop?
I changed the return type to int.
public static int Positive () {
int limit = 50;
int sum = 0;
for(int i=1; i <= limit; i++){
System.out.print(i + ", ");
sum += i;
}
return sum;
}
Another approach
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
You havent cleared yet that you want to return the value or just print it from the function so you can use either of the approach in answers of your question. One with int type can return the value and print as well
Here is what you can do
public static void Positive () {
int limit = 50;
int total = 0;
for(int i=1; i <= limit; i++){
total = total + i;
}
System.out.print(total);
}

Prime numbers calculator takes too much time (JAVA)

When I run this code to find sum of prime numbers below 20 it works fine, but when try to find sum below 2500000 it takes too much time. It's been at least 20 minutes and it's still running. It seems like it's not working. How do I fix it?
class PrimeSummation {
public static void main(String[] args) {
int sum = 0;
for(int i = 1; i < 2500000; i++) {
int count = 0;
for(int j = 1; j < i + 1; j++) {
if((i%j) == 0) {
count++;
}
}
if(count == 2) {
sum += i;
}
}
System.out.println(sum);
}
}
sum cannot be an int because the answer is 219697708195 whereas Integer.MAX_VALUE is only 2147483647. You must use a long or a BigInteger instead.
Your algorithm is very slow, because for every one of the 2500000 numbers you are starting from scratch to decide whether it is prime or not, and your approach for testing whether a number is prime (try every possible factor) is not very efficient.
The following code produces the answer in about a tenth of a second on my machine.
int num = 2500000;
long sum = 0;
boolean[] arr = new boolean[num];
for (int p = 2; p < num; p++) {
if (!arr[p]) {
sum += p;
for (int k = p * 2; k < num; k += p)
arr[k] = true;
}
}
System.out.println(sum);
Keeping track of previously found primes seems to help:
BigInteger sum = BigInteger.ZERO;
List<Integer> primes = new ArrayList<>();
for(int i = 2; i < 2500000; i++) {
boolean isPrime = true;
for(int j = 0; j < primes.size() && primes.get(j)<= Math.sqrt(i); j++) {
int p = primes.get(j);
if((i%p) == 0) {
isPrime=false;
break;
}
}
if(isPrime) {
sum = sum.add(BigInteger.valueOf(i));
primes.add(i);
}
}
System.out.println(sum);
Came up with answer:
219697708195
If you want better performance for generating a large number prime number, you should use Sieve formula.
You can Learn Sieve_of_Eratosthenes formula for prime number generation.
According to Sieve_of_Eratosthenes:
import java.util.*;
public class Sieve
{
private BitSet sieve;
private Sieve() {}
private Sieve(int size) {
sieve = new BitSet((size+1)/2);
}
private boolean is_composite(int k)
{
assert k >= 3 && (k % 2) == 1;
return sieve.get((k-3)/2);
}
private void set_composite(int k)
{
assert k >= 3 && (k % 2) == 1;
sieve.set((k-3)/2);
}
public static List<Integer> sieve_of_eratosthenes(int max)
{
Sieve sieve = new Sieve(max + 1); // +1 to include max itself
for (int i = 3; i*i <= max; i += 2) {
if (sieve.is_composite(i))
continue;
// We increment by 2*i to skip even multiples of i
for (int multiple_i = i*i; multiple_i <= max; multiple_i += 2*i)
sieve.set_composite(multiple_i);
}
List<Integer> primes = new ArrayList<Integer>();
primes.add(2);
for (int i = 3; i <= max; i += 2)
if (!sieve.is_composite(i))
primes.add(i);
return primes;
}
}
Performance:

Writing a temp. array

Ive already wrote code that will take the temp for each month and then show and calculate the total, average, most and least rainfall for the year and output that. How do I replace the most and least rainfall with actually months names?
code so far:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Rainfall
{
public static void main(String[] args)
{
String [] months={"Janurary","Febuary","March","April","May","June","July","August","September","October","November","December"};
final int MONTHS = 12;
double[] rain = new double[MONTHS];
initRain(rain);
double total = totalRain(rain);
double average = averageRain(rain, total);
int most = mostRain(rain);
int least = leastRain(rain);
// Decimal Format
DecimalFormat digit = new DecimalFormat("#.0");
// Output
System.out.println("The total rainfall of the year is " + digit.format(total));
System.out.println("The average rainfall of the year is " + digit.format(average));
System.out.println("The month with the highest amount of rain is " + (most + 1));
System.out.println("The month with the lowest amount of rain is " + (least + 1));
}
public static void initRain(double[] array)
{
Scanner keyboard = new Scanner(System.in);
for (int x = 0; x < array.length; x++)
{
System.out.print("Enter Rainfall for month " + (x + 1) + ": ");
array[x] = keyboard.nextDouble();
}
}
public static double totalRain(double[] array)
{
double total = 0;
for (int x = 0; x < 12; x++)
total += array[x];
return total;
}
public static double averageRain(double[] array, double total)
{
return total / array.length;
}
public static int mostRain(double[] array)
{
double maximum = array[1];
int value = 0;
for (int i=0; i < 12; i++) {
if (array[i] >= maximum) {
maximum = array[i];
value = i;
}
}
return months[index];
}
public static int leastRain(double[] array)
{
double minimum = array[0];
int value = 0;
for (int i=0; i < 12; i++)
{
if (array[i] <= minimum) {
minimum = array[i];
value = i;
}
}
return value;
}
}
Well, you've got an index, and you've got an array of the names of the months, so... ?
String most = months[mostRain(rain)];
I guess that this code is not even compiling
see
public static int mostRain(double[] array)
{
double maximum = array[1];
int value = 0;
for (int i=0; i < 12; i++) {
if (array[i] >= maximum) {
maximum = array[i];
value = i;
}
}
return months[index];
}
as it is expecting to be returned an int but you are returning a String (also index does not exist), so what you want is
public static int mostRain(double[] array)
{
double maximum = 0.00; // change this too
int value = 0;
for (int i=0; i < 12; i++) {
if (array[i] >= maximum) {
maximum = array[i];
value = i;
}
}
return value; // change this
}
then you can use it above like
System.out.println("The month with the highest amount of rain is " + months [mostRain (rain)]);
Of course, make the similar change for leastRain too.

Need help retrieving largest index from array

I'm stuck... My code was working earlier, but now it just hangs. On top of that I can't seem to get my getHighest and getSmallest methods to return the correct values. I don't know if I'm just not catching something. Any help would be great!
import java.util.Scanner;
import java.text.DecimalFormat;
public class Rainfall
{
public static void main(String[] args)
{
final int MONTHS = 12;
double[] rain = new double[MONTHS];
initRain(rain);
double total = totalRain(rain);
double average = averageRain(rain, total);
double most = mostRain(rain);
double least = leastRain(rain);
DecimalFormat digit = new DecimalFormat("#.0");
System.out.println("The total rainfall of the year is " + digit.format(total));
System.out.println("The average rainfall of the year is " + digit.format(average));
System.out.println("The month with the highest amount of rain is " + most);
System.out.println("The month with the lowest amount of rain is " + least);
}
public static void initRain(double[] array)
{
Scanner keyboard = new Scanner(System.in);
for (int x = 0; x < array.length; x++)
{
System.out.print("Enter Rainfall for month " + (x + 1) + ": ");
array[x] = keyboard.nextDouble();
}
}
public static double totalRain(double[] array)
{
double total = 0;
for (int x = 0; x < 12; x++)
total += array[x];
return total;
}
public static double averageRain(double[] array, double total)
{
return total / array.length;
}
public static double mostRain(double[] array)
{;
double maximum = array[1];
int value = 0;
for (int i=0; i < 12; i = i++)
{
if (array[i] >= maximum)
maximum = array[i];
value = i;
}
return value;
}
public static double leastRain(double[] array)
{
double minimum = array[0];
int value;
for (int i=0; i < 12; i++)
{
if (array[i] <= minimum)
minimum = array[i];
value = i;
}
return value;
}
}
Your program hangs because of this line:
for (int i=0; i < 12; i = i++)
The problem is that i++ returns the value of i before the variable is incremented, so the increment step of your loop is the same as writing i=i. Thus, the variable i never reaches the escape condition of the loop.
it should be:
for (int i=0; i < 12; i++)
Cleaned up your code a little bit, can be improved a lot. There were many simple errors.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Rainfall
{
public static void main(String[] args)
{
final int MONTHS = 12;
double[] rain = new double[MONTHS];
initRain(rain);
double total = totalRain(rain);
double average = averageRain(rain, total);
int most = mostRain(rain);
int least = leastRain(rain);
DecimalFormat digit = new DecimalFormat("#.0");
System.out.println("The total rainfall of the year is " + digit.format(total));
System.out.println("The average rainfall of the year is " + digit.format(average));
System.out.println("The month with the highest amount of rain is " + (most + 1));
System.out.println("The month with the lowest amount of rain is " + (least + 1));
}
public static void initRain(double[] array)
{
Scanner keyboard = new Scanner(System.in);
for (int x = 0; x < array.length; x++)
{
System.out.print("Enter Rainfall for month " + (x + 1) + ": ");
array[x] = keyboard.nextDouble();
}
}
public static double totalRain(double[] array)
{
double total = 0;
for (int x = 0; x < 12; x++)
total += array[x];
return total;
}
public static double averageRain(double[] array, double total)
{
return total / array.length;
}
public static int mostRain(double[] array)
{
double maximum = array[1];
int value = 0;
for (int i=0; i < 12; i++) {
if (array[i] >= maximum) {
maximum = array[i];
value = i;
}
}
return value;
}
public static int leastRain(double[] array)
{
double minimum = array[0];
int value = 0;
for (int i=0; i < 12; i++)
{
if (array[i] <= minimum) {
minimum = array[i];
value = i;
}
}
return value;
}
}

Categories