import java.util.Scanner;
import java.util.Arrays;
public class Improved {
//I resize the array here so that it only counts inputs from the user
//I want to ignore the 0 input from the user
//I think the error happens here or in my main method
public static double[] resizeArray(double[] numbers, double size) {
double[] result = new double[(int)size];
for (int i = 0; i < Math.min(numbers.length, size); ++i) {
result[i] = numbers[i];
}
return result;
}
//compute average nothing is wrong here
public static double getAverage( double[] numbers) {
double sum = 0;
for (int i = 0; i < numbers.length; ++i)
sum += numbers[i];
double average = sum/numbers.length;
return average;
}
//SD nothing is wrong here
public static double getSD( double[] numbers, double average) {
double sd = 0;
for ( int i = 0; i < numbers.length; ++i)
sd += ((numbers[i] - average)*(numbers[i] - average)/ numbers.length);
double standDev = Math.sqrt(sd);
return standDev;
}
//maximum nothing is wrong here
public static double getMax( double[] numbers) {
double max = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] > max){
max = numbers[i];
}
return max;
}
//minimum nothing is wrong here
public static double getMin( double[] numbers) {
double min = numbers[0];
for (int i = 1; i < numbers.length; ++i)
if (numbers[i] < min) {
min = numbers[i];
}
return min;
}
//median value nothing is wrong here
public static double getmed( double[] numbers) {
double median;
if (numbers.length % 2 == 0)
median = (((numbers[numbers.length/2 - 1])
+ (numbers[numbers.length/2]))/2);
else
median = numbers[numbers.length/2];
return median;
}
//the problem is in the main method i think or in the call method to resize
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] statArr = new double[99];
double size = 0;
int i = 0;
System.out.println("Type your numbers: ");
double number = input.nextDouble();
//I don't want the zero in the array, I want it to be excluded
while (number != 0){
statArr[i] = number;
i++;
number = input.nextDouble();
++size;
if ( size == statArr.length) {
statArr = resizeArray(statArr, statArr.length * 2);
}
++size;
}
statArr = resizeArray(statArr, size);
java.util.Arrays.sort(statArr);
double average = getAverage(statArr);
System.out.println( "The average is " + getAverage(statArr));
System.out.println( "The standard deviation is " + getSD(statArr, average));
System.out.println( "The maximum is " + getMax(statArr));
System.out.println( "The minimum is " + getMin(statArr));
}
}
// I don't have any concerns with computing the math parts, but I can't seem to make it so my array ignores the 0 that ends the while loop. In other words, I want every number included up until the user enters the number 0. Everything else is right. Thank you very much!
You have ++size twice. This means your resizeArray method won't work correctly:
double[] result = new double[(int)size];
Here you're allocating more than what you actually want. This is why you're getting zeroes in your array. Java arrays are initialized to 0 (in case of numeric primitive types).
As Giodude already commented, I suggest you using List implementations (typically ArrayList) instead of arrays everytime you can.
Also size could be declared as int altogether and avoid that cast (and save some extremely slight memory), you're not using it as a double anywhere.
Related
So I have an assignment where i'm supposed to create a program that generates 100 random integers and stores them in a single dimensional array. I am then supposed to calculate the average, standard deviation and variance. Through a lot of trial and error I was able to make a program that did this but what I missed was that it said to write a separate method for each property(average, standard deviation and variance). How would i go about doing that?
package homeassignment5;
public class HomeAssignment5 {
public static void main(String[] args) {
int n;
n = 100;
int[] random = new int [n];
for (int i = 0; i<random.length; i++)
random[i] = (int) (Math.random()* n);
double total = 0;
double average = 0;
double variance = 0;
double var = 0;
double sd = 0;
for (int element : random){
total += element;
average = total/n;
}
for (int i = 0; i<random.length; i++){
variance += (random[i] - average) * (random[i] - average);
}
var = variance / random.length;
sd = Math.sqrt(var);
//System.out.println("Total is: " + total);
System.out.println("Average is: " + average);
System.out.println("Variance is " + var);
System.out.println("Standard deviation is " + sd);
/*for (int i = 0; i<random.length; i++)
System.out.println(random[i]);
*/
}
}
Might be a bit of a mess but i'm really new to java and this was the product of a ton of trial and error.
So there are several ways of going about this, but the easiest would probably be this:
public class HomeAssignment5 {
private static int[] random;
public static void main(String[] args){
random = = new int[100];
...
}
public static void getAverage(){
// void if you want to print it here, double if you want to print in main
double average = 0;
int total = 0;
for(int i = 0; i < 100; i += 1)
total += random[i];
average = total / n; // you'll want to do this outside of the loop to
// to get the correct result!
System.out.println("Average: " + average);
}
...
}
You could alternatively pass the array to each method as a parameter.
By the way, in what you posted here, you still haven't actually written any random numbers into the array, so remember to do that, it's currently still all zero.
I believe this should help you..
All the functionalities are separated in form of methods,
the initialization is separated.
** WELCOME TO REFACTORING **
public class Refactor {
private int[] random;
private int n;
private double total = 0;
private double average = 0;
private double variance = 0;
private double sd = 0;
public Refactor(int n) {
this.n = n;
this.populateArray();
}
private void populateArray() {
random = new int[n];
for (int i = 0; i < random.length; i++)
random[i] = (int) (Math.random() * n);
}
public double getAverage() {
average = 0;
total = 0;
for (int element : random) {
total += element;
}
average = total / n;
return average;
}
public double getVariance() {
variance = 0;
for (int i = 0; i < random.length; i++) {
variance += (random[i] - average) * (random[i] - average);
}
variance = variance / random.length;
return variance;
}
public double getSD() {
this.getVariance();
sd = 0;
sd = Math.sqrt(variance);
return sd;
}
public static void main(String[] args) {
Refactor ref = new Refactor(100);
System.out.println("Average is: " + ref.getAverage());
System.out.println("Variance is " + ref.getVariance());
System.out.println("Standard deviation is " + ref.getSD());
}
}
How would i go about passing the array to each method?
The first and most straightforward of the three methods is average:
static double average(int [] r)
{ double total = 0;
for (int e: r) total += e;
return total/r.length;
}
For the second method, the standard deviation, I recommend not to pass the array, but rather the variance, since if the program has calculated the variance anyway, it need not be recalculated, and if it doesn't have, the SD method can be called with a call to the variance method as its argument.
static double SD(double variance) { return Math.sqrt(variance); }
For the third method, the variance, I recommend not only to pass the array, but also its average, with similar reasoning as above.
static double variance(int [] r, double average)
{ double var = 0;
for (int e: r) var += (e - average) * (e - average);
return var/r.length;
}
With those three methods defined, you can now replace
double total = 0;
double average = 0;
double variance = 0;
double var = 0;
double sd = 0;
for (int element : random){
total += element;
average = total/n;
}
for (int i = 0; i<random.length; i++){
variance += (random[i] - average) * (random[i] - average);
}
var = variance / random.length;
sd = Math.sqrt(var);
with
double average = average(random);
double var = variance(random, average);
double sd = SD(var);
Write a program that contains two overloaded methods that return the average of an array with the following headers:
public static int average(int[] array)
public static double average(double[] array)
my program contains the errors
list2[i] = sc.nextDouble(); // possible lossy conversion from double to int
return average; // possible lossy conversion from double to int
not sure what the problem is I have declared within my methods what needs to be declared I don't know why my double in put would give me that error
import java.util.Scanner;
public class Lab7A {
public static void Main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter 10 Integer values: ");
int list[] = new int[10];
for (int i = 0; i < list.length; i++) {
list[i] = sc.nextInt();
}
double avg1 = average(list);
System.out.println("Average of First Array: " + avg1);
System.out.println();
System.out.print("Enter Ten Double Values: ");
double list2[] = new double[10];
for (double i = 0; i < list2.length; i++) {
list2[i] = sc.nextDouble();
}
double avg2 = average(list2);
System.out.println("Average of Second Array: " + avg2);
System.out.println();
}
public static int average(int[] list) {
double average = 0;
double total = 0;
for (int i = 0; i < list.length; i++) {
total = total + list[i];
}
average = total / list.length;
return average;
}
public static double average(double[] list2) {
double average = 0;
double total = 0;
for (int i = 0; i < list2.length; i++) {
total = total + list2[i];
}
average = total / list2.length;
return average;
}
}
Your average(double[]) method is attempting to use a double as an array index, but Java only allows ints as an array index. This is the source of the "possible lossy conversion from double to int".
Everything else is and should be double, but declare your index d as int to remove this error.
Additionally, in the for loop of that method, the condition should be d < list2.length instead of d < 5.
Also, the average of int values may not necessarily be an int. In your average(int[]) method, declare it to return a double, and declare average to be a double. The variable avg1 will need to be a double in main also.
I am trying to write a program that takes an integer as command-line argument, uses random to print N uniform random values between 0 and 1, and then prints their average value.
I'm not sure what arguments to put in the while loop so that random integers are repeated n times, n being the number from the user indicating the number of integers the random has to generate.
Any help would be appreciated.
enter code here
public class UniformRandomNumbers1 {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int i;
double total = 0.0; //(The sum of n, numbers)
for (i = 1; i <= n; i++) {
double rand = Math.random(); //(Random number between 0 & 1)
total += rand; // Increment total by rand
System.out.println(i + " = " + rand); // Prints value of n & corresponding double value
}
double average = total / n; // Calculates average of n numbers
System.out.println("Average = " + average); // Prints average of n numbers, Can i get an up vote? :) plz
}
}
if you just need to execute a loop a specific number of times, I'd use a for loop
The following loop will iterate exactly n times, and It's what I personally use when I need to do something exactly n times.
for(int i=0; i<n; i++)
{
//insert body here
}
int total = 0;
for (int current = 1; current <= n; n++) {
double rand = Math.random();
total += rand;
System.out.println(currentN + "= " + rand);
}
System.out.println("Total = " + total);
under the assumption that your PRNG is behaving correcly you just need this:
main()
{
printf("\n0.5");
exit(0);
}
that's for N sufficiently large... computed in constant time. otherwise use the moving average formula:
http://en.wikipedia.org/wiki/Moving_average
which requires only O(1) memory space instead of the naive O(N) approach
here the cut&paste java code:
public class Rolling {
private int size;
private double total = 0d;
private int index = 0;
private double samples[];
public Rolling(int size) {
this.size = size;
samples = new double[size];
for (int i = 0; i < size; i++) samples[i] = 0d;
}
public void add(double x) {
total -= samples[index];
samples[index] = x;
total += x;
if (++index == size) index = 0; // cheaper than modulus
}
public double getAverage() {
return total / size;
}
}
For some reason my computePositiveSum final output for "The sum of the positive numbers" is wrong when a negative number is entered before any positive numbers. It seems like what's happening is instead of ignoring the negative numbers it subtracts it's sum from the total. So if my input was (-4,2,3) it would say the sum of positive numbers was 1. I'm not really sure what is wrong with the method.
/* Description: Write a program that reads in a sequence of numbers
(not necessary integers) from standard input until 0
is read, and stores them in an array. This is done
using iteration (choose for, while, or do while loop).
You may assume that there will not be more than 100 numbers.*/
import java.util.Scanner;
import java.text.DecimalFormat;
public class Assignment2
{
public static void main (String[] args)
{
Scanner scan= new Scanner(System.in);
int count=0;
double[] num= new double[100];
for(int i=0;i<num.length;++i)
{
num[i]= scan.nextDouble();
if (num[i] == 0) {
break; }
count++;
}
double min= findMin(num,count);
double pos= computePositiveSum(num, count);
int c= countNegative(num,count);
DecimalFormat fmt = new DecimalFormat ("0");
DecimalFormat fmt2 = new DecimalFormat ("$0.00");
System.out.println("The minimum number is " +fmt.format(min));
System.out.println("The sum of the positive numbers is "+fmt2.format(pos));
System.out.println("The total number of negative numbers is " +c);
}//End Main
public static double findMin(double[] num, int count)
{
double min = num[0];
for(int i=1;i<count;i++){
if(num[i] < min)
{
min = num[i];
}
}
return min;
}//end findMin
public static double computePositiveSum(double[] num, int count)
{
double pos=num[0];
for(int i=1;i<count;i++){
if(num[i] > 0)
{
pos=pos+num[i];
}
}
return pos;
}
public static int countNegative(double[] num, int count)
{
double a=num[0];
int c=0;
for(int i=0;i<count;i++){
if(num[i] < 0)
{
c++;
}
}
return c;
}//end countNegative
}
You are assigning to the actual sum pos the value of the first element in the array. So if the first element is negative it will be added to the sum (there is no check in the code to know if it's positive or not).
To fix this, initialize the sum pos (by the way, it is not a descriptive name) with 0. Then iterate in the for loop from 0, not from 1.
public static double computePositiveSum(double[] num, int count)
{
double pos = 0;
for (int i = 0; i < count; i++) {
if (num[i] > 0) {
pos = pos + num[i];
}
}
return pos;
}
Note: I would recommend you to name your variables with a more descriptive name. I would have declared pos with the name sum. Of course this has nothing to do with the result, but is useful for people to understand the code.
because you are doing
double pos = num[0];
then going through the remainder of the array you need to do
double pos = 0;
for (int i = 0; ...)
You're not checking the first element of the array
public static double computePositiveSum(double[] num) {
double sum = 0.0;
for(double d : num) {
if(d > 0) {
sum += d;
}
}
return sum;
}
You need to check if element 0 is greater than zero.
this code doesn't function,
it said that lessthaAverage(int) in calculateArray cannot be applied to (), I'm a beginner so I still don't understand this coding yet, this is the question ask, Write an object oriented program that randomly generates an array of 1000 integers between 1 to 1000.
Calculate the occurrences of number more than 500 and find the average of the numbers.
Count the number which is less than the average and finally sort the numbers in descending order.
Display all your output. Please do HELP ME!!!,Thank You...
import java.util.*;
import java.io.*;
//import java.util.random;
public class CalculateArray
{
//declare attributes
private int arr[] = new int[1000];
int i;
//generates an array of 1000 integers between 1 to 1000
public void genArr()
{
Random ran = new Random();
for(i = 0; i < arr.length; i++)
{
arr[i] = ran.nextInt(1000) + 1;
}
}
//Calculate the occurences of number more than 500
public int occNumb()
{
int count;
for(i = 0; i < arr.length; i++)
{
if(arr[i] > 500)
{
count++;
}
}
return count;
}
//find the average of the numbers
public int average()
{
int sum, aver;
for(i = 0; i < arr.length; i++)
{
sum += arr[i];
}
aver = sum/1000;
return aver;
}
//Count the number which is less than the average
public int lessthanAverage(int aver)
{
int cnt;
cnt = 0;
for(i = 0; i < arr.length; i++)
{
if(arr[i] < aver)
{
cnt++;
}
}
return cnt;
}
//finally sort the numbers in descending order.
public void sort(int[] num)
{
System.out.println("Numbers in Descending Order:" );
for (int i=0; i <= num.length; i++)
for (int x=1; x <= num.length; x++)
if (num[x] > num[x+1])
{
int temp = num[x];
num[x] = num[x+1];
num[x+1] = temp;
}
}
//Display all your output
public void display()
{
int count, aver;
System.out.println(arr[i] + " ");
System.out.println("Found " + count + " values greater than 500");
System.out.println("The average of the numbers is " + aver);
System.out.println("Found " + count + " values that less than average number ");
}
public static void main(String[] args)
{
CalculateArray show = new CalculateArray();
show.genArr();
int c= show.occNumb();
show.average();
int d=show.lessthanAverage();
show.sort(arr);
show.display();
}
}
Your method lessthanAverage is expecting a int parameter. You should store the result of the average method call into a int variable and pass it to the call to lessthanAverage.
int avg = show.average();
int d=show.lessthanAverage(avg);
Your lessthaAverage() method expects an average to be passed in as a parameter, but you are not passing it in when you call it.
It seems that your method lessthanAverage needs an int as a parameter, but you are not passing it in main
public int lessthanAverage(int aver)
In main aver is not being passed:
int d=show.lessthanAverage(); // where is aver?
But if you wanted to know the average inside the method you could call your average method inside lessthanAverage:
if(arr[i] < this.average())
and not pass any parameter at all:
public int lessthanAverage()