5.16 LAB: Adjust list by normalizing
When analyzing data sets, such as data for human heights or for human weights, a common step is to adjust the data. This adjustment can be done by normalizing to values between 0 and 1, or throwing away outliers.
For this program, adjust the values by dividing all values by the largest value. The input begins with an integer indicating the number of floating-point values that follow. Assume that the list will always contain fewer than 20 floating-point values.
Output each floating-point value with two digits after the decimal point, which can be achieved as follows:
System.out.printf("%.2f", yourValue);
Ex: If the input is:
5 30.0 50.0 10.0 100.0 65.0
the output is:
0.30 0.50 0.10 1.00 0.65
The 5 indicates that there are five floating-point values in the list, namely 30.0, 50.0, 10.0, 100.0, and 65.0. 100.0 is the largest value in the list, so each value is divided by 100.0.
For coding simplicity, follow every output value by a space, including the last one.
I have been confused about how to do floating-point values in arrays and loops as in my book it never went over that.
Scanner scnr = new Scanner(System.in);
double numElements;
numElements = scnr.nextDouble();
double [] userList = new double [numElements];
int i;
double maxValue;
for (i = 0; i < userList.length; ++i) {
userList[i] = scnr.nextDouble();
}
maxValue = userList[i];
for (i = 0; i < userList.length; ++i) {
if (userList[i] > maxValue) {
maxValue = userList[i];
}
}
for (i = 0; i < userList.length; ++i) {
userList[i] = userList[i] / maxValue;
System.out.print(userList[i] + " ");
System.out.printf("%.2f", userList[i]);
}
}
}
It's outputting:
LabProgram.java:8: error: incompatible types: possible lossy conversion from double to int
double [] userList = new double [numElements];
I am confused about how to move forward, any help will be much appreciated!
Just change the data type of numElements to int and the scanner command to int as well
Like this:
int numElements = scnr.nextInt();
Related
I am tasked to create a program where i am supposed to to store the 10 numbers in an array of doubles. Then i have to calculate mean, variance, and standard deviation.
Everything works fine besides the variance and, in turn, the standard deviation (i believe the code works for Std Dev).
I have put copied a sample output and a desired output for your convenience.
Thank you!
package Statistics;
import java.util.Scanner;
public class Statistics {
public static void main(String[] args) {
double values[] = new double[10];
//Declaring variables
double sum1 = 0.0, mean;
double variance, sum = 0.0;
Scanner scanner = new Scanner(System.in); //scanner to allow user to input
System.out.print("Enter the 10 numbers: ");
for (int i = 0; i < values.length; i++) {
values[i] = scanner.nextDouble();
}
for (int i = 0; i < values.length; i++)
{
sum1 += values[i];
}
mean = sum1 / values.length;
for (int i = 0; i < values.length; i++)
{
sum += Math.pow(values[i] - mean, 2);
}
variance = sum / (values.length - 1);
double standardDeviation = Math.sqrt(variance);
System.out.printf("\nMean : %.1f", mean); //calculate mean
System.out.printf("\nVariance : %.2f", variance); //calculate variance
System.out.printf("\nStandard Deviation : %.2f", standardDeviation); //calculate StdDev
scanner.close(); //close the scanner
}
}
Desired Output:
Enter the 10 numbers: 5
8
10
6
12
3
5
7
9
-2
Mean : 6.3
Variance : 14.01
Standard Deviation : 3.74
Sample output:
Enter the 10 numbers: 5
8
10
6
12
3
5
7
9
-2
Mean : 6.3
Variance : 15.57
Standard Deviation : 3.95
You're using the wrong formula for variance. Instead of variance = sum / (values.length - 1); try variance = sum / values.length; and you should get:
Mean : 6.3
Variance : 14.01
Standard Deviation : 3.74
The variance formula is sum / the length of values. Your std depends on the variance for the correct answer. Hence, why both are incorrect. If space isn't a concern - try doing each step a line at a time, then combine them to once it is working.
I am a beginner in Java and I am being asked to write a program to find the average of three grades. I am trying to figure out how to get a double output by type casting but I don't know where to cast. I have already written some code myself but the grader is still saying I'm not getting the right answer.
Here are the program instructions:
In the code below, type in three made up int grades and then sum and
average them. Use casting to report the result as a double. For
example, if the grades are 90, 100, and 94, the sum of the three
numbers is 90 + 100 + 94 = 284, and the average is the sum 284 divided
by 3 which casted to a double is 94.666667. You should use your
variables instead of the numbers in your formulas. Follow the
pseudocode below.
Type in three made up int grades and then sum and average them. Use
type casting to report the result as a double.
Here is my code:
public class Challenge1_6
{
public static void main(String[] args)
{
// 1. Declare 3 int variables called grade1, grade2, grade3
// and initialize them to 3 values
int grade1 = 78;
int grade2 = 95;
int grade3 = 84;
// 2. Declare an int variable called sum for the sum of the grades
int sum;
// 3. Declare a variable called average for the average of the grades
int average;
// 4. Write a formula to calculate the sum of the 3 grades (add them up).
sum = grade1 + grade2 + grade3;
// 5. Write a formula to calculate the average of the 3 grades from the sum using division and type casting.
average = sum / 3;
// 6. Print out the average
System.out.println(average);
}
}
This is my output (It wants a decimal but I don't know how to get it):
enter image description here
Well the average variable must be double
and you cast the division result to fit in the average variable
double average;
// 4. Write a formula to calculate the sum of the 3 grades (add them up).
sum = grade1 + grade2 + grade3;
// 5. Write a formula to calculate the average of the 3 grades from the sum using division and type casting.
average = (double) sum / 3;
System.out.println(average);
Simply change the variable "average" to double.
double average=Double.valueOf(sum / 3);
Logic is:
At least one variable in the function (a/b) should be the type of double
Or we need to convert the int value to Double as required.
You can simply divide by the double literal 3.0 or 3d so that it performs floating point division instead of instead divison.
double average;
sum = grade1 + grade2 + grade3;
average = sum / 3.0;
Demo!
Just convert the average to double to avoid any missing due to the cast from double to int
public class Challenge1_6 {
public static void main(String[] args) {
int grade1 = 78;
int grade2 = 95;
int grade3 = 84;
int sum;
double average;
sum = grade1 + grade2 + grade3;
average = sum / 3;
System.out.println(average);
}
}
I want to print 0.5000 value in java therefor I try BigDecimal for this purpose but when i divide i get 0.5 with red color.
Can i print 0.5000 using BigDecimal if not then why and why does 0.5 print in red font?
My code is:
static void plusMinus(int[] arr) {
Double n = 0.0, p = 0.0, z = 0.0;
for(int i = 0; i < arr.length; i++) {
if(arr[i] < 0) n++;
else if(arr[i] > 0) p++;
else z++;
}
n = BigDecimal.valueOf(n/arr.length).setScale(4,RoundingMode.HALF_UP).doubleValue();
p = BigDecimal.valueOf(p/arr.length).setScale(4,RoundingMode.HALF_UP).doubleValue();
z = BigDecimal.valueOf(z/arr.length).setScale(4,RoundingMode.HALF_UP).doubleValue();
System.err.println(p); // print:0.5 //(in red font)
System.out.println(n); // print:0.3333
System.out.println(z); // print:0.1667
}
n = BigDecimal.valueOf(n/arr.length).setScale(4,RoundingMode.HALF_UP).doubleValue();
The result of the right hand side is a double: and it gets autoboxed to a Double to assign it to the left hand side. When you print n, you're not printing a BigDecimal, but rather a Double.
There is no such thing as a Double (or a double) 0.5000 as distinct from a Double (or a double) 0.5. 0.5000 == 0.5: they are the same value.
Since there is no scale information stored in a Double (or a double), there is no way of knowing that you want 0.5000 as opposed to 0.5 or 0.500000000.....000.
If you want to print with a certain number of decimal places, either use a NumberFormatter of some flavour, or keep it as a BigDecimal.
Trying to take my sumDanceScore method and divide each element in my danceScore array by the return value of sumDanceScore; however, when It just keeps comming back 0. I have placed println's to show that there are two legitamate integers there however it is always ==0 please help!
package javasandbox;
import java.util.*;
public class JavaSandbox {
public static int sumDanceScore(int danceScore[], int first, int last)
{
if (first > last)
{
return 0;
}
else
{
int total = sumDanceScore(danceScore,first+1,last) + danceScore[first];
return total;
}
}
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
System.out.println("Enter number of contestants : ");
int numContest = kbd.nextInt();
int danceScore[] = new int[numContest + 1];
int first = 0;
int last = danceScore.length - 1;
System.out.println("Enter dance scores: ");
int numContestIndex;
for (numContestIndex = 1; numContestIndex <= numContest; numContestIndex++)
{
danceScore[numContestIndex] = kbd.nextInt();
}
int danceScoreTotal = sumDanceScore(danceScore, first, last);
System.out.println("SUM DANCE SORE METHOD: "+danceScoreTotal);
for(int danceScoreIndex = 1; danceScoreIndex <= danceScore.length-1; danceScoreIndex++)
{
System.out.println("DANCE SCORE INDEX NUMBER: "+danceScore[danceScoreIndex]);
int danceScoreShare = danceScore[danceScoreIndex] / danceScoreTotal;
System.out.println("DANCER SHARE PERCENT: "+danceScoreShare);
}
}
}
You need to cast the ints to a floating point number (float or double) first †. danceScoreShare is going to be a fraction, so it should also be a float or double.
double danceScoreShare = (double)danceScore[danceScoreIndex] / (double)danceScoreTotal;
Your danceScoreTotal will always be bigger than danceScore[danceScoreIndex], so with java integer division you will always get a 0 result.
† actually you can just cast one of the right hand arguments and binary numeric promotion does the other
The technical details from the JLS:
... the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| ≤ |n|.
So, for example, with the division 9 / 10, you can see that |10 · 1| = 10 which is greater than |9|. Therefore it returns 0.
It's obvious that on dividing each element in my danceScore array by the bigger return value of sumDanceScore, the return value will sure be 0 because of the int/int division.
The rule says that in numerator/denominator division,
if numerator < denominator,then the result will be 0 due to truncation in int.
int(smaller)/int(bigger_sum) ~= 0.some_value = 0 (in terms of result as int)
Example :-
4/20 = 0.20(in double) = 0 (for int result).
The workaround is to use float/double as the data-type for the division variable.
Working on a project where the user input determines the size of an array. Afterwards the user inputs values and receives the sum. Finally the program shows the user the percentage of each value to the total. For example if the array size is 4 and a[0] = 2, a[1] = 1, a[2] = 1, and a[3] = 2 it will show "2, which is 33.333% of the sum" "1, which is 16.666% of the sum" etc. The problem I have is that after the array and sum are determined and I try to find the percentage I get 0. Is the sum reset to 0 since it's a different for loop?
import java.util.Scanner;
public class CountIntegersPerLine
{
public static void main(String[] args)
{
int elements;
int arraySize;
int sum = 0;
int percentage;
System.out.println("How many numbers will you enter?");
Scanner keyboard = new Scanner(System.in);
//Length of array is determined by user input
arraySize = keyboard.nextInt();
int[] array = new int[arraySize];
System.out.println("Enter 4 integers, one per line");
for (elements = 0; elements < arraySize; elements++)
{
//Gather user input for elements and add the total value with each iteration
array[elements] = keyboard.nextInt();
sum = sum + array[elements];
}
System.out.println("The sum is " + sum);
System.out.println("The numbers are:");
for (elements = 0; elements < arraySize; elements++)
{
//Display the percent that each value contributes to the total
percentage = array[elements] / sum;
System.out.println(array[elements] + ", which is " + percentage + " of the sum.");
}
System.out.println();
}
}
Integer division will result in a zero value when the numerator is less than the denominator. You should declare percentage as a float or a double.
int percentage;
...
...
...
percentage = array[elements] / sum;
and you will need to cast the division operation in your case to preserve the value:
percentage = (double)array[elements] / sum;
Try declaring the sum variable as a double (or float):
double sum = 0.0;
Why? because in this line:
percentage = array[elements] / sum;
... You're performing a division between two integers, and all the decimals will be lost. You can verify that this is indeed the case, for example try this:
System.out.println(1/3); // it'll print 0 on the console
The solution to this problem is to have either one of the division's operands as a decimal number, by declaring as such their types (as I did above) or by performing a cast. Alternatively, this would work without changing sum's type:
percentage = array[elements] / ((double)sum);