I would like to generate an array of 100 numbers and find their average and sum. I am able to do this but I am not able to get the output of numbers into ascending order. I am super new to Java.
import java.util.Random;
public class randomNumberGen
{
public static void main(String [] args)
{
Random r=new Random();
double sum = 0; // is double so to prevent int division later on
int amount = 100;
int upperBound = 100;
for (int i = 0; i < amount; i++){
int next = r.nextInt(upperBound) + 1; // creates a random int in [1,100]
System.out.println(next);
sum += next; // accumulate sum of all random numbers
}
System.out.println("Your average is: " + (sum / amount));
System.out.println("Your sum is: " + (sum));
}
}
it is very easy. however I didn't see any array in your code. I create an example code for you. you can ask for more help.
public static void main(String[] args) {
SecureRandom random = new SecureRandom(); // it is better to use this library
double sum = 0; // is double so to prevent int division later on
int amount = 100;
int upperBound = 100;
int[] array = new int[amount]; // create an array with amount size
for (int i = 0; i < amount; i++) {
array[i] = random.nextInt(upperBound) + 1; // creates a random int in [1 , upperBound]
sum += array[i]; // accumulate sum of all random numbers
}
Arrays.sort(array); // sort array in default order which is ascending
System.out.println(Arrays.toString(array)); // toString is a way to print all of array, without iterate it and print it
System.out.println("Your average is: " + (sum / amount));
System.out.println("Your sum is: " + sum);
}
There are a lot of different sorting methods. For a beginner start with either Bubble Sort or Insertion Sort. Insertion Sort is slightly better as on average it runs slightly faster.
I offer to use one of special collections to sort numbers internally, without using one of sorting algorithms (e.g. us PriorityQueue):
public static void main(String[] args) {
final int amount = 100;
Random random = new SecureRandom();
Queue<Integer> queue = new PriorityQueue<>(amount, Comparator.naturalOrder()); // Comparator.reverseOrder() for reverse order
int sum = 0;
for (int i = 0; i < amount; i++) {
int val = random.nextInt(100) + 1;
sum += val;
queue.add(val);
}
System.out.println(Arrays.toString(queue.toArray()));
System.out.println("Your average is: " + (double)sum / amount);
System.out.println("Your sum is: " + sum);
}
Related
The purpose of this program is to intake 5 values (test scores) from the user, then output the average score. I am not familiar with arrays so I really don't have the slightest clue what I'm doing wrong. All I know is the double 'sum' cannot be set equivalent to the int ' total'. Sorry for being dumb but I'M TRYING HERE :)
import java.util.Scanner;
public class Main
{
public static void main (String [] args)
{
int x = 0;
double testScore[] = new double[5];
double sum[] = new double[5];
double total;
int avg;
Scanner keys = new Scanner(System.in);
System.out.println("Enter the values of 5 separate test scores that you have received: \n");
for (int i = 0; i < testScore.length; i++)
{
x++;
System.out.println("Enter your grade for test number " +1);
double score = keys.nextDouble();
score = testScore[i];
sum = testScore;
sum = (int)total;
avg = ((total) / 5);
System.out.print("The sum of your grades is " +avg +"\n");
}
}
}
double sum = 0;
for (double score: testScore) {
sum += score;
}
double avg = sum / testScore.length;
Here you go, I tried not to change much of your code so you can still understand what I changed!
public static void main(String[] args) {
double testScore[] = new double[5];
double sum = 0;
double avg;
Scanner keys = new Scanner(System.in);
System.out.println("Enter the values of 5 separate test scores that you have received: \n");
for (int i = 0; i < testScore.length; i++) {
System.out.println("Enter your grade for test number " + 1);
double score = keys.nextDouble();
sum += score;
avg = sum / 5;
System.out.print("The sum of your grades is " + avg + "\n");
}
}
Basically, all you need is the sum variable, you can get the avg from it!
first i would declare your variables like this:
int x = 0;
double[] testScore = new double[5];
double[] sum = new double[5];
double total;
int avg;
A few changes to be made:
You don't want to set score to testscore[i] because its null so flip that. If you want to cast the doubles to integers use Integer.valueOf(). You should also place them outside the for loop and calculate sum in the for loop, as shown:
for (int i = 0; i < testScore.length; i++)
{
x++;
System.out.println("Enter your grade for test number " +1);
double score = keys.nextDouble();
testScore[i] = score;
sum += Integer.valueOf(score);
total += score;
}
avg = Integer.valueOf(total / testScore.length);
System.out.print("The sum of your grades is " +avg +"\n");
I haven't tested this code but i hope it helps.
In order to get the sum of all elements of an array, you will need to iterate over it:
Scanner keys = new Scanner(System.in);
double[] testScore = new double[5];
double sum = 0.0;
for (int i = 0; i < testScore.length; i++) {
// We don't need to use x, we already have i
System.out.println("Enter your grade for test number " + (i + 1));
double score = keys.nextDouble();
testScore[i] = score; // Store the grade into the element #i of the array
// We can instantly process the data we have to collect. Otherwise we must
// walk a second time over the elements
sum = sum + score; // Or the shorthand notation: sum += score
}
double avg = sum / testScore.length;
System.out.println("The average of your grades is " + avg + "\n");
I modified the following things to your code:
You are using two arrays (testScore and sum) having the same function. Both are meant to store the grades in it. I removed one of them.
I removed x, because i fulfills its function already.
I changed the type of your variable avg to a double. Feel free to change it back to an int, but then the average's decimals will be truncated (for instance, 4.6 will be 4).
I'm trying to find the maximum value of the last column and i need to print it out. I tried using the Double.max(); method but it doesn't work for the specific array and I wanted to create an array for the 13th column but it won't let me.
import java.lang.reflect.Array;
public class LabMidterm3 {
public static void main(String[] args) {
double[][] myArray =new double [4][13];
double row = myArray.length;
double column = myArray[0].length;
for (int i=0; i<row;i++){
int sum =0;
for(int j=0; j<column;j++){
double random = (int)(Math.random()*7.0);
myArray[i][j] = random;
sum+=myArray[i][j];
System.out.print(myArray[i][j] + ", ");
double max = Array.getDouble(myArray, 13);
if(j==13){
System.out.print("The max value is: " + max);
}
}
double rowAverage= sum/column;
if(i==1){
System.out.println();
System.out.print("The average is: " +rowAverage);
System.out.println();
}
System.out.println();
}
}
Since you are calculating (and storing) double values, don't cast the random to an int. Next, initialize max to some non-present value guaranteed to be smaller than any value present (like -∞). Then use Math.max(double, double) to update it while you iterate the row. And you can use Arrays.toString(double[]) to print your row. Finally, print the average and max after you populate the array. Something like
double sum = 0;
double max = Double.NEGATIVE_INFINITY;
for (int j = 0; j < column; j++) {
myArray[i][j] = Math.random() * 7.0;
max = Math.max(max, myArray[i][j]);
sum += myArray[i][j];
}
System.out.println(Arrays.toString(myArray[i]));
double rowAverage = sum / column;
if (i == 1) {
System.out.println("The average is: " + rowAverage);
System.out.println("The max is: " + max);
}
I am trying to generate three random integers between 0 and 50, calculate the average, and print the result.
This is what I have so far:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package random.numbers;
import java.util.Random;
/**
*
* #author ericl_000
*/
public class RandomNumbers {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Random rand = new Random ();
int RandNum = 0;
for(int i =0; i < 3; i++)
{
RandNum = rand.nextInt(50);
System.out.println(RandNum);
}
int average = (RandNum);
System.out.println(average);
}
}
The output has the 3 random numbers, but the average is the last number of those 3 numbers. I don't know how to get the average of these 3 numbers. (I am new with Java.)
Your logic for calculating average is not correct, logic for average is:
average = (num1+num2+num3+... .... +num N)/N
So your logic for code should be:
Random rand = new Random();
int RandNum = 0;
float average = 0;
for(int i =0; i < 3; i++)
{
RandNum = rand.nextInt(50);
System.out.println(RandNum);
average = average+RandNum;
}
average = average/3;
System.out.println(average);
Example Code:
import java.util.Random;
public class RandomNumbers {
public static void main (String [] args) {
Random rand = new Random();
int randomNum = 0, total = 0;
int count = 3;
for(int i = 0; i < count; i++)
{
// This gives you 0 to 49, does not include 50!
randomNum = rand.nextInt(50);
System.out.println(randomNum);
// Keep track of total
total += randomNum;
}
// Average is well, total divided by count
int average = total / count;
System.out.printf("Average (Integer division): %d%n", average);
// Using double
double averageDouble = total / ((double) count);
System.out.printf("Average (Double division): %7.3f%n", averageDouble);
}
}
Output:
3
26
8
Average (Integer division): 12
Average (Double division): 12.333
Note:
Using integer or double for division will give u different results!
random#nextInt(int n) gives you a value between 0 (inclusive) and the specified value (exclusive), i.e. nextInt(50) will give you 0 to 49.
and how would you compute the average in real life? You add the numbers up, and you divide by 3.
int sum=0;
for(i=0; i<3; i++)
sum += rand.nextInt(50);
System.out.println(sum/3.0);
You are not saving the random numbers as they are generated.
for(int i =0; i < 3; i++)
{
RandNum = rand.nextInt(50);
System.out.println(RandNum);
}
For each iteration of the loop, a random number is generated and printed.
But is nowhere saved.Then how can you access them later to calculate the average.
Try something like this
for(int i =0; i < 3; i++)
{
RandNum += rand.nextInt(50);
}
This will add generated random number to already generated one.So bascially
RandNum will contain the sum at the end of all iterations of the loop.
Then you can use the following to print the average.
System.out.println(RandNum/3);
Just by naming a variable 'average', it wont find the average.You have to do the necessary calculation.ie.(sum/n).
Not sure why this is a complicated problem.
import java.util.Random;
public class RandomNumbers {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Random rand = new Random ();
int randCount = 3, randNum = 0, total = 0;
for(int i =0; i < randCount; i++) {
randNum = rand.nextInt(50);
System.out.println(randNum);
total = total + randNum;
}
int average = total/randCount;
System.out.println(average);
}
}
The average formula is the sum of all the numbers in a list divided by number by the number of items in that list. You can do this by constantly adding the random numbers up into a variable, lets call it x, then divide that by 3 (total number of items in that list).
for(int i =0; i < 3; i++)
{
RandNum = rand.nextInt(50);
System.out.println(RandNum);
int x += RandNum; //the += sign adds the current value of x to the value of RandNum
}
int average = (x/3);
System.out.println(average);
This answer assumes that you will be only using 3 random numbers.This is using ints however you should probably use doubles considering most averages aren't exact integers:
double RandNum = 0;
for(int i =0; i < 3; i++)
{
RandNum = rand.nextDouble(50);
System.out.println(RandNum);
double x += RandNum; //the += sign adds the current value of x to the value of RandNum
}
double average = (x/3);
System.out.println(average);
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
Random rand = new Random ();
int RandNum = 0;
int[] numbers = new int[]{rand.nextInt(50),rand.nextInt(50),rand.nextInt(50)};
double sum = 0;
for(int i =0; i < 3; i++)
{
System.out.println(numbers[i]);
}
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];
double average = sum / numbers.length;
System.out.println("Average value of array elements is : " + average);
}
}
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;
}
}
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.