how to get the standard deviation - java

idk if i have to get the standard while in the loop or out of the loop.also can you help me understand why it is i do it inside the loop or out and what the difference is. also i know the standard deviation formula in this situation would be something like (input - average)^2 for the first then ++ for every value after then add all that up and divide by the count then square root that. im just not fully sure how to write it and where to put it
import java.util.Scanner;
public class readFromKeyboard {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String inStr = input.next();
int n;
int count=0;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
double average=0;
int sum;
double deviation = 0;
while (!inStr.equals("EOL")) {
count++;
n = Integer.parseInt(inStr);
min = Math.min(min, n);
max = Math.max(max, n);
System.out.printf("%d ", n);
inStr = input.next();
average += n;
}
average = average/count;
System.out.println("\n The average of these numbers is " + average);
System.out.printf("The list has %d numbers\n", count);
System.out.printf("The minimum of the list is %d\n", min);
System.out.printf("The maximum of the list is %d\n", max);
input.close();
}
}

Given that you already calculated average, now you can calculate the standard deviation for each number.
Create array sd[] to store the standard deviation.
For each number, sd[i] = (average - input_i) ^ 2
Calculate variance:
For each standard deviation in sd[], add to a variable temp
Divide temp by total number of inputs
Calculate population standard deviation:
Square root variance

Related

How to fix getting an average from user input

The instructions are the following:
Write a method called inputThenPrintSumAndAverage that does not have any parameters.
The method should not return anything (void) and it needs to keep reading int numbers from the keyboard.
When the user enters something that is not an int then it needs to print a message in the format "SUM = XX AVG = YY". XX represents the sum of all entered numbers of type int.
YY represents the calculated average of all numbers of type long.
I've coded the following method but I keep getting the incorrect average. What can I change to get the correct average?
public static void inputThenPrintSumAndAverage(){
Scanner scanner = new Scanner(System.in);
int sum = 0, counter = 0;
long average = 0L;
while(true) {
boolean number = scanner.hasNextInt();
if(!number)
{
counter++;
break;
}
else {
int digit = scanner.nextInt();
sum += digit;
counter++;
}
}
average = sum / counter;
System.out.println("SUM = " + sum + " AVG = " + average);
}
The following should do:
if(!number)
break;
Your average is wrong because you are incrementing "counter" more than you should.
Of course in the end you are going to have to add one more if statement to make sure you are not attempting to divide by counter if the counter is zero. In that case, an average is undefined.
Also, as others have pointed out in the comments, it is entirely unclear to us what you mean when you say "I keep getting the incorrect average", and we generally frown upon questions worded so vaguely. But if by any chance a "correct average" for you means an average with decimals, then you should use a double instead of a long for your average, and you should cast your counter to double before dividing, so as to force a double division instead of a long division.
Use scanner.hasNextInt() to read util a non-integer value is supplied as input:
public static void inputThenPrintSumAndAverage() {
Scanner scanner = new Scanner(System.in);
int number, sum = 0, counter = 0;
long average = 0L;
while (scanner.hasNextInt()) {
number = scanner.nextInt();
sum += number;
counter++;
}
if(counter != 0){
average = sum / counter;
}
System.out.println("SUM = " + sum + " AVG = " + average);
}
Note that you should check the value of counter to avoid a division by zero.
If you want the average to be in decimals, change the type of average to double: double average; and cast the division to double: average = (double) sum / counter;.

Reading in a number.txt file and finding averages

currently working on an assignment and I need to read in a file of numbers and display the total amount of numbers, total even numbers, total odd numbers, and the averages of all three. I am currently struggling to find the average of the even numbers and the odd numbers. I have to display the average of the even number and the average of the odd numbers. I found the total average by using parseInt to convert the string of numbers i read in to ints so i could calculate the average but when i tried to do the same for even and odd numbers i couldnt get it to work
here is my current code:
public class Homework1 {
public static void main(String[] args) throws IOException {
// reads file in
File num = new File("numbers.txt");
Scanner inputFile = new Scanner(num);
// creates rounding object
DecimalFormat rounding = new DecimalFormat("#.##");
// neccesary variables
int count = 0;
double numbers =0;
int evenNum =0;
int oddNum =0;
double avg;
double evenAvg;
double oddAvg;
double sum = 0.0;
double evenSum = 0.0;
double oddSum = 0.0;
// reads in numbers file until last line is read
while(inputFile.hasNext())
{
String nums = inputFile.nextLine();
// converts string to ints so numbers can be added
sum += Integer.parseInt(nums);
// converts string to ints to so odd/even nums can be distinguished
numbers = Integer.parseInt(nums);
// updates total number count
count++;
// separates evens from odds
if(numbers % 2 == 0)
{
evenNum++;
evenSum += Integer.parseInt(nums);
}
else
oddNum++;
evenSum += Integer.parseInt(nums);
}
// calculates total num average
avg = sum/count;
// evenAvg =
// oddAvg =
// output of credentials and results
System.out.println("There are " +count+ " numbers in the file"+"\n");
System.out.println("There are " +evenNum+ " even numbers"+"\n");
System.out.println("There are " +oddNum+ " odd numbers"+"\n");
System.out.println("The total average value is " +rounding.format(avg)+"\n");
System.out.println("The odd number average is " +rounding.format(evenAvg)+"\n");
System.out.println("The even number average is " +rounding.format(oddAvg)+"\n");
}
Output:
There are 982 numbers in the file
There are 474 even numbers
There are 508 odd numbers
The total average value is 50362.43
okay so I corrected the if/else statements and added the brackets and this fixed the problem i was having
oddNum++;
oddSum += Integer.parseInt(nums);

how to get the sum, average, minimum and maximum of five numbers-java using do-while loop

I'm trying to get the sum, average, minimum and maximum of five numbers but somehow I get this output. I'm trying to re-code it all over again but it is still the same. Can you help me check this guys...
Here's my code:
import java.util.*;
public class Kleine {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double average;
int count = 0, sum = 0, num, min = 0, max = 0;
System.out.println("Please enter the number of numbers you wish to evaluate:");
do {
num = scan.nextInt();
sum += num;
count++;
} while (count < 5);
average = sum / 5;
{
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
System.out.println("Your average is: " + average);
System.out.println("The sum is: " + sum);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
}
}
Here's the output:
Please enter the number of numbers you wish to evaluate:
1
10
5
-3
6
Your average is3.0
The sum is:19
Your maximum number is 6
Your minimum number is 0
BUILD SUCCESSFUL (total time: 19 seconds)
The minimum and maximum numbers goes somewhere...
a little advice please...
The best way to handle the min/max values is to keep track of them as your read in each value:
int sum = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i=0; i < 5; ++i) {
num = scan.nextInt();
if (num > max) max = num;
if (num < min) min = num;
sum += num;
}
double average = sum / 5.0d;
I seed the max and min values with the smallest/largest integer values, respectively. This lets us capture the actual min and max values as they are read in. Also, I think that a basic for loop works better here than a do while loop.
Note that I compute the average using a double type, because it may not be a pure integer value (even in your sample data the average is not an integer).
Use
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
And your
{
if(num>max)
max=num;
if(num<min)
min=num;
}
needs to be inside the do-while loop, or else it runs only for the last value of number entered.
For a start you can use Math.min & Math.max. The average is sum / count.
An example getting a min number without a loop would be:
long min = Integer.MAX_VALUE;
min = Math.min(min, 9);
min = Math.min(min, 4);
min = Math.min(min, 6);
// min = 4
Do something similar for max.
You'd also be better off starting with a list or array of numbers. Get the output right, then add more complicated things like user input.
You can do it this way without defining number of integers to read:
import java.util.ArrayList;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
Scanner in = new Scanner(System.in);
while (true) {
System.out.println("Next number?");
numbers.add(in.nextInt());
IntSummaryStatistics summaryStatistics = numbers.stream()
.mapToInt(Integer::valueOf)
.summaryStatistics();
System.out.println(String.format("Max: %d, Min: %d, Average: %s, Sum: %d", summaryStatistics.getMax(), summaryStatistics.getMin(), summaryStatistics.getAverage(), summaryStatistics.getSum()));
}
}
}
If I just change the existing code, the logic should be like below:
do{
num=scan.nextInt();
sum+=num;
if(count==0){
min=num;
max=num;}
if(num>max)
max=num;
if(num<min)
min=num;
count++;
}while(count<5);
average = sum/5;
The issue was that your min-max condition was outside the loop and you were initializing min and max by 0. You should set min/max to your first input number.
Min and Max were now equal to the max and min of integer. now if any number is less than min and greater than max, min and max takes their position. The average and the sum functionality was great. The problem in your code was that it was getting the max and min after the loop for input has executed. The flow was wrong.
import java.util.*;
public class Kleine {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
double average;
int count=0, sum=0, num=0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
System.out.println("Please enter the number of numbers you wish to evaluate:");
do{
if(num>max) max=num;
if(num<min) min=num;
num=scan.nextInt();
sum+=num;
count++;
}while(count<5);
average = sum/5;
System.out.println("Your average is"+average);
System.out.println("The sum is:"+sum);
System.out.printf("Your maximum number is %d\n",max);
System.out.printf("Your minimum number is %d\n",min);
}
}

Count numbers in a "for loop" and give back average, min, max value in java

A user should input a number "x", and then the count of "x" numbers, e.g. input = 3, then 3 random numbers like 3, 5, 7.
Afterwards the program should give an output of the average, min and max value of this "x" numbers. So it has to read the numbers, but i don't know how it can be done.
It should be done without arrays and with a for loop.
I didn't find a possible solution here, but maybe I didn't do the right search.
So here is what i got so far:
import java.util.Scanner;
public class Statistic
{
public static void main (String[] args)
{
// Variables
Scanner input = new Scanner(System.in);
int number1;
int numbers;
double averageValue;
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Pls enter a number: ");
number1 = input.nextInt();
System.out.print(" Pls enter " + number1 +" numbers: ");
numbers = input.nextInt();
for (int count = 0; count < number1; count ++) {
System.out.println(numbers); //Just for me to see which numbers are read by the programm
}
averageValue = numbers / number1;
// Output
System.out.println("\n Biggest number: " + Math.max(numbers));
System.out.println("\n Smallest number: " + Math.min(numbers));
System.out.print("\n Average value: " + averageValue);
}
}
But it only prints out and calculates with the first number of the "numbers"-input. Further I am not sure how to use the "Math.max" for a random count of numbers.
The problem is here:
System.out.print(" Bitte geben Sie " + number1 +" Zahlen ein: ");
numbers = input.nextInt();
nextInt() only saves one int. Every subsequent number you are entering gets lost, of course.
What you need to do is to move this statement inside the for loop for your idea to work.
Also, you can't use min and max here. min and max compare two numbers and return the greater of the two. For your purpose, you'd need to check inside the loop which the greatest and smallest number is and then output it accordingly.
You will need 6 variables: min = 0, max = 0, avg, sum = 0, count, num.
(avg variable is optional)
Program flow will be:
input how many numbers you want to enter -> store in variable count
use some loop to loop count number of times and in each iteration store
users value in variable num.
Increment sum by number user entered. sum += num;
check if entered number is less than current min. If true store min as that number.
Same as min do for max variable.
When loop exit you will have min, max, sum and count variables stored. To calculate avg devide sum with count and there you go. avg = sum / count.
First your code is logically in correct. when u have to take min and max values with average u need to store the inserted elements or process each input(for time complexity this would be the best approach).
Below I have modified your code where i m using enter code hereJava Collections List to store the inputs, sort them and get the data.
After sorting first will me min and last will be max.
Math.min and Math.max only works for comparing 2 numbers not an undefined list.
Again i would say the best solution would be if u check for the number is min or max at input time.
As you are new to java you can try that out your self.
import java.util.*;
public class ZahlenStatistik
{
public static void main (String[] args)
{
// Variables
Scanner input = new Scanner(System.in);
int number1;
List<Integer> numbers = new ArrayList<Integer>(); // change it to list
double averageValue;
int sum= 0;
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Bitte geben Sie eine Zahl ein: ");
number1 = input.nextInt();
System.out.print(" Bitte geben Sie " + number1 +" Zahlen ein: ");
//Define the number of times loop goes
for (int count = 0; count < number1; count ++)
{
numbers.add(input.nextInt());
}
for(Integer number:numbers)
{
sum = sum + number;
}
averageValue = sum / number1;
Collections.sort(numbers);
// Output
System.out.println("\n Die größte Zahl ist: " + numbers.get(numbers.size()-1));
System.out.println("\n Die kleinste Zahl ist: " + numbers.get(0));
System.out.print("\n Der averageValue betr\u00e4gt: " + averageValue);
}
}
Some errors that I can see
System.out.print(" Pls enter " + number1 +" numbers: ");
numbers = input.nextInt();
You need here a loop and array to read and store all elements.
To get average value you need first to sum all elements in array and then to divide by length of array.
To find min and max values in array you cannot use Math.min() and Math.max() methods because these methods get two parameters and return min/max value.
Your code should be something like this
Notes
If you cannot use Java 8 you must replace Arrays.stream(numbers).max().getAsInt(); and Arrays.stream(numbers).min().getAsInt(); with helper methods which find max/min values in an array.
If you can use Java 8 you can calculate sum int sum = Arrays.stream(numbers).reduce(0, (x, y) -> x + y); instead in for loop.
.
public class Statistic {
public static void main(String[] args) {
// Variables
Scanner input = new Scanner(System.in);
// Input
System.out.println("\n\n####################################################################");
System.out.print("\n Pls enter a number: ");
int number1 = input.nextInt();
System.out.println(" Pls enter " + number1 + " numbers: ");
int[] numbers = new int[number1];
for (int i = 0; i < number1; i++) {
System.out.println("Enter next number");
numbers[i] = input.nextInt();
}
// Find min and max values
int max = Arrays.stream(numbers).max().getAsInt();
int min = Arrays.stream(numbers).min().getAsInt();
System.out.println("\n Biggest number: " + max);
System.out.println("\n Smallest number: " + min);
// Get average value
int sum = 0;
for (int num : numbers) {
sum = sum + num;
}
double averageValue = (double) sum / number1;
System.out.print("\n Average value: " + averageValue);
}
}
import java.util.Scanner;
public class SumOf2
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter 2 integer values");
int m = s.nextInt();
int n = s.nextInt();
int sum=0;
int count=0;
for(int i=m ; i<=n ; i++)
{
if(count < n)
{
sum=sum+i;
count++;
}
}
System.out.println("Sum of two numbers is: "+sum);
System.out.println("Count between 2 numbers is : "+count);
}
}

Java Input and Out put

Hi my code should do this instruction below but am not getting it at all
The user can enter as many positive floating-point numbers on the console as desired. Zero (or a
negative numbers) signals end of input (no more numbers can be entered). After input the program
displays
 the smallest number entered (min)
 the largest number entered (max)
 the mean of all numbers entered (mean)
Do NOT use arrays for this assignment, even if you know them.
Sample should look like this
enter numbers: \n
1 2 3 4 5 6 0 \n
numbers entered: 6 \n
minimum: 1.00 \n
maximum:6.00 \n
mean: 3.50\n
enter numbers: \n
0 \n
no number entered.
public class LoopStatistics {
public static void main(String[] args) {
double max, min, sum=0, input, mean=0;
int counter = 0;
TextIO.putln("enter numbers:");
do
{
input = TextIO.getDouble();
min = input;
max = input;
counter++;
if (input > max)
max = input;
if ( input < min)
min = input;
sum = sum + input;
} while( input != 0);
mean = sum / counter;
TextIO.putf("numbers entered:%d\n", counter);
TextIO.putf("minimum:%f\n", min);
TextIO.putf("maximum:%f\n", max);
TextIO.putf("mean:%f", mean);
}
}
You assign your max and min before you test whether they are greater/less than the current max/min:
min = input;
max = input;
This means that they both equal whatever the person entered last.
Tidying up your code and removing those calls yields:
public static void main(String[] args) throws Exception {
final Scanner scanner = new Scanner(System.in);
double max = 0;
double min = Double.POSITIVE_INFINITY;
double sum = 0;
int counter = 0;
while (true) {
final double d = scanner.nextDouble();
if (d <= 0) {
break;
}
sum += d;
max = Math.max(max, d);
min = Math.min(min, d);
++counter;
}
System.out.println("Max=" + max);
System.out.println("Min=" + min);
System.out.println("Ave=" + sum / counter);
}

Categories

Resources