So after browsing the already asked questions on here and other sites I figured I would give this a go.
I am working on an exercise that wants you to set up a program in Java that takes an input of 10 numbers and computes the average(mean) and the standard deviation and outputs them.
My problem is that when I run the program, and then enter my desired 10 values and hit enter, nothing happens. For some reason the System printouts that occur after the loop are not being executed. The println inside the loop is not necessary, but is just to show that the values are being calculated correctly as the loop runs, and they are.
I am aiming to have the current value that myValues is assigned to to be added to sum1, and the square of myValues to be added to the sqrdSum. sqrdSum is just a variable I made to sum the squares of the values entered so that the calculation of standard deviation later in the program will be cleaner.
As expected, I am not looking for this to be done for me, just some advice on how to adjust my code such that the printlns at that occur after the loop will execute. I am expecting it to be something to do with my logic, but can not figure it out. Hopefully it is something simple I have managed to miss.
Thanks.
So far I have set it up using a for loop:
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = sum1 / n;
double std1 = Math.pow((sqrdSum - (Math.pow(sum1, 2) / n)) / (n-1), 0.5);
Scanner input1 = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double myValues = input1.nextDouble();
for (int count = 0; count <= n; count++) {
sum1 += myValues;
sqrdSum += Math.pow(myValues, 2);
System.out.println(sum1 + " " + sqrdSum); //this is to test to see if the loop is calculating correctly.
myValues = input1.nextDouble();
}
System.out.print("The mean of your values is: " + mean1);
System.out.print("The standard deviation of your values is: " + std1);
//Test values: 1 2 3 4.5 5.6 6 7 8 9 10
//Should give a mean of 5.61
//std of 2.99794
The problem is, that input1.nextDouble() blocks until the next number is entered. You are entering 10 numbers, but you expect 11 inputs, since you have this line
double myValues = input1.nextDouble();
which executes once and
myValues = input1.nextDouble();
inside the loop which executes 11 times. Just move it at the beginning of the loop:
Scanner input1 = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double myValues = 0;
for (int count = 0; count < n; count++) {
double myValues = input1.nextDouble();
sum1 += myValues;
sqrdSum += Math.pow(myValues, 2);
System.out.println(sum1 + " " + sqrdSum); //this is to test to see if the loop is calculating correctly.
}
As Brian noted, you also have an off-by-one error. You start at 0 but count to 10, that makes 11 loop cycles. Change <= to <
Just change count <= n to count < n in your cycle. You're accidentaly expecting one too many values.
While the answers given did solve your original problem there is also another problem with your code. You won't be getting the correct mean because of how you initiate it and then don't set it to any values after your for loop.
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = sum1 / n;
double std1 = Math.pow((sqrdSum - (Math.pow(sum1, 2) / n)) / (n-1), 0.5);
The lines above should read,
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = 0.0;
double std1 = 0.0;
and then after your for loop you should calculate mean1 and std1 like the code below.
int n = 10;
double sum1 = 0.0;
double sqrdSum = 0.0;
double mean1 = 0.0;
double std1 = 0.0;
Scanner input1 = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double myValues = 0.0;
for (int count = 0; count < n; count++) {
myValues = input1.nextDouble();
sum1 += myValues;
sqrdSum += Math.pow(myValues, 2);
System.out.println(sum1 + " " + sqrdSum); //this is to test to see if the loop is calculating correctly.
}
mean1 = sum1 / n;
std1 = Math.pow((sqrdSum - (Math.pow(sum1, 2) / n)) / (n-1), 0.5);
System.out.print("The mean of your values is: " + mean1);
System.out.print("The standard deviation of your values is: " + std1);
//Test values: 1 2 3 4.5 5.6 6 7 8 9 10
//Should give a mean of 5.61
//std of 2.99794
Related
the question is to find the sum of this series
series
i used this code to solve it , but im not quite sure the logic is correct.
the noofterms is how many terms are going to be added
and x is the number that will be assigned to the variable.
does the logic seem correct?
public static double sumOfSeries(double x, int noofterms){
double evennumbers=1;
double oddnumbers=1;
double result=1;
// since the power of x starts from 1 , we start i from 1 and increment by 2
for (int i=1; i<noofterms; i+=2 ){
// we reset starting numbers so we start from them everytime
evennumbers = 1;
oddnumbers = 1;
// everytime the number increases by 2 when it is smaller than i+1
// ex when its equal to 2 , j = 3 , j+1 = 4 so it increments by 2
// when its 4 , j = 5 , j+ 1 = 6 , it increments
for (int j=2; j<=i+1; j+=2){
// multiply by increments of 2
evennumbers= evennumbers * j;
}
// it starts from 1 and increments by 2 so it goes like 1,3,5
for (int z=1; z<=i; z+=2){
oddnumbers = oddnumbers * z;
}
result*=((Math.pow(x, (double)i)) / (double)i) + (oddnumbers/evennumbers);
}
return result;
}
You can do it better. Note that numerators and denominators form two sequences, so you can keep previous terms to efficiently make computations, this will look like this :
long even = 1;
long odd = 1;
double result = x;
for(long i = 1; i < noofterms; i++)
{
even *= 2 * i;
odd *= 2 * i - 1;
double oper = Math.pow(x, (double)(2 * i + 1)) / (double)(2 * i + 1);
result += (double)even / (double)odd * oper;
}
You can improve by using logarithms because even and odd will grow very fast and will lead to overflows :
double even = 0.0;
double odd = 0.0;
double result = x;
double logx = Math.log(x);
for(long i = 1; i < noofterms; i++)
{
even += Math.log((double)(2 * i));
odd += Math.log((double)(2 * i - 1));
double oper = logx * (2 * i + 1) - Math.log((double)(2 * i + 1));
result += Math.exp(even - odd + oper);
}
EDIT: only one sequence could also be computed : p *= (double)(2*i)/(2*i-1). Then the log trick is not useful.
This question already has answers here:
Why doesn't my "While Loop" print the computation of finding the average "score"?
(5 answers)
Closed 7 years ago.
So I have a public accessor method called gettSeconds and I have called it in a while loop as below 20 times:
int i =0;
double sum = 0;
double average =0;
while (i < 20) {
call.read();
sum = sum + call.getSeconds();
System.out.println(sum);
average = sum / 10.0;
}
So basically I called read 20 times and then I calculate how long it took to read the file each time and average the total time.But I keep getting my last time as my average instead of the actual average.
I am enticed to change much more - but lets keep as much as possible of your original - you probably want to do something like this?
double sum = 0;
double average =0;
for (int i=0; i < 20; i++) {
call.read();
sum = sum + call.getSeconds();
}
average = sum / 20.0;
System.out.println(average);
Note that for your original while (i < 20) - the condition is always true, so in effect it would run forever. Maybe you had different intentions - in that case, please be more clear.
You should be calculating the average after summing all the values:
int i = 0;
int sum = 0;
int average = 0;
while (i < 20) {
call.read();
sum = sum + call.getSeconds();
}
average = sum / 20.0;
We can simplify this by using a for loop and the += operator:
int sum = 0;
for (int i = 0; i < 20; i++) {
sum += call.read().getSeconds();
}
int average = sum / 20.0;
I want this while loop to print every multiple of two below the number submitted(ex. if 100 was submitted it would print 2 4 8 16 32 64). Here's what I have(I'm only going to include a portion of the class because there was other things in it that don't pertain to this part)
i = 1;
Scanner myScanner = new Scanner(System.in);
System.out.print("Would thoughst be inclined to enter a number fair sir/madam: ");
String answer = myScanner.nextLine();
int number = Integer.parseInt(answer);
System.out.print("Your number set is: ");
while(i <= number)
{
i = 2*i;
System.out.print(" " + i + " ");
}
What this prints if I enter 100 is: 2 4 8 16 32 64 128
How do I get rid of that last number?
You would get rid of that number by modifying your logic to match. Your code is doing precisely what it says. One option is to start at 2, and increase i at the end of the loop instead of just before printing it. You could also use a for loop:
for (int i = 2; i < 100; i *= 2)
...
If you want to save the last power, you have a few options, e.g.:
int k = 2;
for (int i = k; i < 100; i *= 2) {
k = i;
...
}
Or undo the last operation:
int i;
for (i = 2; i < 100; i *= 2)
...;
i /= 2;
Or check the next one:
int i;
for (i = 2; i * 2 < 100; i *= 2)
...;
Checking the next one, in your original form:
while (i * 2 <= number)
...;
Etc.
By the way, your title says "factors", your description says "multiples", and your code says "powers"...
In your code
while(i <= number)
{
i = 2*i;
System.out.print(" " + i + " ");
}
the problem is that i, when it is equal to 64, is indeed less than 100, so the loop continues.
If you change it to
i = 2*i;
while(i <= number)
{
System.out.print(" " + i + " ");
i = 2*i;
}
it does as you wish, because it pre-computes the value before being analyzed as the while-loop terminator.
Try
while( i <= number / 2)
Those are powers of 2, not factors of 2.
"thoughst" is not a word. It should be "thou".
Update the value of i after you print it.
double Hg = Double.parseDouble(values2[17]);
for (int i = 0; i < 3; i++) {
double Avg = (Hg + Hg + Hg) / 3;
System.out.println(Avg);
}
My program reads a file and puts everything in a String array called values2. The array element #17 (values2[17]) contains the values I need. I converted that array element into a double so I could then calculate the average. The program should take the first 3 values that are in values[17] and then divide by 3 to calculate the average, but it is just printing out the same values 3 times instead of adding and then dividing.
Any thoughts of what I am doing wrong?
If I understand what you're doing (comma seperated String of values), it could be as simple as...
public static void main(String[] args) {
String[] values = new String[18];
values[17] = "1.0, 2.0, 4.0";
double total = 0;
int count = 0;
for (String v : values[17].split(",")) {
if (v != null) {
total += Double.valueOf(v.trim());
count++;
}
}
double avg = total / ((double) count);
System.out.println("The average of " + values[17] + " is " + avg);
}
Which outputs
The average of 1.0, 2.0, 4.0 is 2.3333333333333335
If values2[17] is a String like "2 5 7", Then you need to parse all them each individually
String[] nums = valus2[17].split(" ");
double d1 = Double.parseDouble(num[0]);
double d2 = Double.parseDouble(num[1]);
double d3 = Double.parseDouble(num[3]);
double average = (d1 + d2 + d3) / 3;
On The other hand if you you have a String like "567" and you want the individual values, can you split into a char array then add the int values
String value = "567" // value2[17]
char[] digits = value.toCharArray();
int total = 0;
for (char c : digits){
total += Integer.parseInt(String.valueOf(c));
}
double average = total / new Double(digits.length);
You don't do anything with the i...
double total= 0.0;
for(int i = 0; i < 3;i++) {
total += values[i];
}
double avarage = total/3.0;
System.out.println(avarage);
Currently you are adding the whole array to itself 3 times then dividing but you need to add the three ideas in the array then divide by three
do
double Avg = values2[0] + values2[1] + values2[2] / 3
I am writing a program where I must ask the user how many assignments they have. Then, I must ask them for their score and the maximum points possible for the assignment. I know how to find the sum of the first set of numbers they entered (their scores) but I am stuck on how I would go about totaling the maximum points possible. Here is what I have so far:
int totalNumber = scan.nextInt();
double sum = 0.0;
for (int i = 1; i <= totalNumber; i++) {
System.out.print("Assignment " + i + " score and max? ");
double score = scan.nextDouble();
double maxScore = scan.nextDouble();
sum += score;
The output looks something like this:
Assignment 1 score and max? 16 17
Assignment 2 score and max? 18 19
I am not sure how I would total the maximum points (17 and 19 in the example) because I must print the total points:
(sum of scores)/(sum of maximum points).
Thanks.
the simple answer is to add another variable for summing the maxScore
int totalNumber = scan.nextInt();
double sum = 0.0;
double maxSum = 0.0;
for (int i = 1; i <= totalNumber; i++) {
System.out.print("Assignment " + i + " score and max? ");
double score = scan.nextDouble();
double maxScore = scan.nextDouble();
sum += score;
maxSum += maxScore;
}