This question already has an answer here:
What does "possible lossy conversion" mean and how do I fix it?
(1 answer)
Closed 4 years ago.
I'm creating a program that stores doubles in an array and then stores each array in an ArrayList then calculates the average from that ArrayList, but I keep getting a "possible lossy conversion from double to int." in line 5.
I'm new to java so I might be overseeing a simple fix.
public static double calculateAll(List<double[]> allNumbers) {
double average = 0.0;
double total = 0.0;
for(int i = 0; i < allNumbers.size(); i++) {
total += allNumbers.get(i);
}
average = total/allNumbers.size();
return average;
}
I am not sure what you are asking in the question, but I think this is what you are looking for.
public static double calculateAll(List<Double> allNumbers) {
double average;
double total = 0.0;
for (Double allNumber : allNumbers) {
total += allNumber;
}
average = total / allNumbers.size();
return average;
}
You were storing an Array Inside a Collection. So I have changed that to Double note that double is native while Double isn't. You can't have double inside a Collection. and then I have converted the for loop into a foreach loop
Here is how you can call this code.
public static void main(String[] args) {
List<Double> doubles = new ArrayList<>();
doubles.add(0.1);
doubles.add(4.1);
double wat = calculateAll(doubles);
System.out.println(wat);
}
So lets take a note of all the changes we have done.
List<double[]> has been replaced with List<Double>.
List now holds items of instance Double
for(int i = 0; i < allNumbers.size(); i++) was changed to for (Double allNumber : allNumbers) this is just a basic for-each loop.
Honestly I would just use java 8 for this, We can do this in 1 line!
public static double calculateAll(List<Double> allNumbers) {
return allNumbers.stream().mapToDouble(e -> e / allNumbers.size()).sum();
}
Related
I have a method which has an array as parameter, I've wanted to pass a double value from it but can't store the value passed from the method.
public static void main(String[] args) {
double [] temperature = {2.5, 10.3, 50.0, 66.7, 77.9, 33.2, 0.33};
double final = averageTemp(temperature);
System.out.println(final);
}
public static double averageTemp(double [] temp){
int size =temp.length ;
double total = 0;
for(int i =0; i<size; i++){
total += temp[i];
}
double average = total/size;
return average;
}
I expect to store the returned "average" in "final" variable and print it.
But getting error.
"final" is a keyword in Java.
Pick a different variable name.
You can try this:
double [] temps = {2.5, 10.3, 50.0, 66.7, 77.9, 33.2, 0.33};
OptionalDouble od = DoubleStream.of(temps).average();
od.ifPresent(average -> {
System.out.println(average);
});
DoubleStream has an average method that calculates the average of the doubles in the array and returns an OptionalDouble. The OptionalDouble is returned in case there is no average to be returned, like, if you send an empty array, you shouldn't return 0 because 0 is still a number. With the OptionalDouble you check if the average is present, and if so, you can get it with optionalDouble.get(); or the method that I used.
You can use this DoubleStream object inside of your averageTemp method. Change the variable of double final = ...; to something like double average = ...;
import java.util.*;
import java.lang.*;
public class MyClass
{
String[] getdata()
{
Scanner in=new Scanner(System.in);
System.out.print("Enter numbers to calculate their average (choose 5 to 10 numbers only : ");
String[] a=in.nextLine().split(" ");
return a;
}
double average(String[] num)
{
double avg;
int tot=0;
int[] numbers = new int[num.length];
int l=num.length;
for(int j=0;j<l;j++)
{
tot=tot+numbers[j];
}
avg=tot/l;
return avg;
}
void results(String[] arr,double avg)
{
int[] numbers1=new int[arr.length];
int ll=arr.length;
System.out.print("The average of the numbers ");
for(int i=0;i<ll;i++)
{
numbers1[i]=Integer.parseInt(arr[i]);
System.out.print(numbers1[i]+" ");
}
System.out.print("is ");
System.out.printf("%.2f",avg);
}
public static void main(String args[])
{
MyClass obj=new MyClass();
String[] x=obj.getdata();
double y=obj.average(x);
obj.results(x,y);
}
}
The code is running successfully but for any given output the average is showing as 0.00.
The code takes in integers with space between them and calculates the average and displays it
Help me fix it. Thanks
You do not initialize your numbers array inside average() method.
Instead of tot=tot+numbers[j]; do the following
tot = tot + Integer.parseInt(num[j]);
And to avoid integer deletion change calculation if avg to the following
avg = 1.0 * tot / l; //this will cast intermediate result of 1.0 * tot to double.
There are several issues with your code:
The only thing int[] numbers shares with String[] num input is length. All items of the array remain zero, which in itself is sufficient to explain zero result
Even though avg is double, tot/l is an int. It could be truncated down to zero, depending on the values inside num.
You need to modify your code to parse Strings from num, and compute total as double. After that the division would return the correct result.
Further, you can avoid multiple parses of strings if you return int[] from getdata() method. Given the small number of inputs, this one is not critical for performance of your code.
You never copy the values from String[] num to your int[] numbers, so when you loop through the whole array numbers, you are going to be summing the default value 0, l times.
You need to use parseInt() on all the values in num to convert it to ints and store them in numbers, then make sure you do float(tot)/l to cast it to a float during the division. This avoids truncation due to integer division.
In the average method you create an empty array called numbers. You're calculating the average based on that array which is empty.
Hope this helps
Your numbers array is wrong in the average function. Please find the corrected code below,
double average(String[] num)
{
double avg;
int tot=0;
int l=num.length;
for(int j=0;j<l;j++)
{
tot=tot+Integer.parseInt(num[j]);
}
avg=tot/l;
return avg;
}
Change the data types as you need.
I'd recommend printing a from getdata() to ensure that your numbers are getting entered correctly. My best guess is taht something in the split command is not working right.
Your problem is your average function. You initializes the array of int[] num, but you did not write the int value in it. You can do that as in the same way as in void results(String[] arr,double avg).
Another problem is, that you get the average avg = tot/l; where tot and l are int values. When you divide 2 integer values the result is an int too and the int value will be written into 'avg'. If the average is a floiting point number (example input "1 2", then the floiting part get cutoff and your programm returns the avg = 1. Therefore the division needs at least one variable, which is double.
This one should work:
double average(String[] num)
{
double avg;
double tot=0;
int l=num.length;
for(int j=0;j<l;j++)
{
tot=tot+Integer.parseInt(num[j]);
}
avg= tot/l;
return avg;
}
In your code you are not initializing the numbers[] array .
double average(String[] num)
{
double avg;
double tot=0;
int[] numbers = new int[num.length];
for(int i=0;i<num.length;i++)
{
numbers[i]=Integer.parseInt(num[i]);
}
int l=num.length;
for(int j=0;j<l;j++)
{
tot=tot+numbers[j];
}
avg=tot/l;
return avg;
}
If you are using > Jdk8 . you can use
double average(String[] num) {
OptionalDouble tot = Arrays.stream(num).mapToInt(s -> Integer.parseInt(s)).average();
return tot.orElse(0.0);
}
}
I know questions about this error have been asked before but my situation is different from all the other ones. I am writing code that comes up with the mean, variance, and standard deviation of a data set. I don't get any errors when compiling the code but when I try to run the code I get an error like this : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Main.main(Main.java:25)
/**
* Main class of the Java program.
*
*/
public class Main {
public static void main(String[] args) {
int sum = 0;
double xBar = 0;
double [] dataSet = {1,2,3,4}; // add data here
int xLenght = dataSet.length;
double [] diffrenceSquared={};
double devSum = 0;
double variance = 0;
double standardDeviation = 0;
for (double n: dataSet)
{
sum += n;
}
xBar = sum/xLenght;
for (int i=0; i<dataSet.length; i++)
{
diffrenceSquared[i] = (xBar-dataSet[i])*(xBar-dataSet[i]);
}
for (double n:dataSet)
{
devSum += n;
}
variance = devSum/xLenght;
standardDeviation = java.lang.Math.sqrt(variance);
System.out.println("x bar ="+xBar);
System.out.println("variance ="+ variance);
System.out.println("Standard Deviation ="+ standardDeviation);
}
}
Please help me!
You have declared diffrenceSquared to be a zero-length array with this declaration:
double [] diffrenceSquared={};
That means that there are no elements to assign, and every index is out of bounds.
You're attempting to assign elements to diffrenceSquared in a loop bounded by dataSet's length, so instead declare it to be that length.
double[] diffrenceSquared = new double[dataSet.length];
double [] diffrenceSquared = new double[dataSet.length];
In Java, arrays are not resizable, so you have to give them the right size from the start.
Alternatively, you can use Lists, which are more flexible.
import java.util.ArrayList;
public class Variance {
// Copy here sum from exercise 63
public static int sum(ArrayList<Integer> list) {
int sum = 0;
for(int i=0; i<list.size(); i++ ){
sum = sum + list.get(i) ;
}
return sum;
}
// Copy here average from exercise 64
public static double average(ArrayList<Integer> list) {
double average = sum(list)/list.size();
return average;
}
public static double variance(ArrayList<Integer> list) {
// write code here
double sumMinusAverage = sum(list) - average(list);
return sumMinusAverage * sumMinusAverage / (list.size()-1);
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(2);
list.add(7);
list.add(2);
System.out.println("The variance is: " + variance(list));
}
}
The program is calculating variance. But when when the list contains the same numbers etc 1-s. The program says the variance is 3, but the answer should be 0.
Can someone give me some direction.
The integer division Luiggi Mendoza has already mentioned is a problem you need to fix, but additionally, your algorithm for computing the variance is not correct. It's not the square of the difference between the sum and the average in the numerator.
You must sum up the differences of the individual elements from the average. Dividing by (list.size() - 1) is correct for the sample variance.
public static double variance(ArrayList<Integer> list) {
double sumDiffsSquared = 0.0;
double avg = average(list);
for (int value : list)
{
double diff = value - avg;
diff *= diff;
sumDiffsSquared += diff;
}
return sumDiffsSquared / (list.size()-1);
}
Be careful when there is only one item in the list. The variance should be 0, but you'll need to check the size to avoid a divide-by-zero exception.
Also, if you ever want the population variance, divide by list.size() instead.
The problem is here:
double average = sum(list)/list.size();
sum(ArrayList<Integer>) returns an int, and sum(list)/list.size() is an integer division, so you'll get an int as result. The decimal part of the division will be truncated.
In order to fix this, you should cast one of the operands of the division to double:
double average = ((double)sum(list))/list.size();
Similar in variance method.
This is unrelated to the main problem, but you should code oriented to interfaces, not to direct class implementations. This means, declare your variables and parameters as List<Integer> instead of ArrayList<Integer>. Here's an example:
public static int sum(List<Integer> list) {
int sum = 0;
for(int i=0; i<list.size(); i++ ){
sum = sum + list.get(i) ;
}
return sum;
}
//...
List<Integer> list = new ArrayList<Integer>();
I have this code but it doesn't work!
public class Trial
{
public static void main (String [] args)
{
int average;
int m = 0;
int [] nums = {1,6,8,9,10,60,72};
average = getAverage(int [] nums);
}
public static int getAverage(int [] a)
{
int sum = 0;
for(int i=0; i<a.length; i++)
sum = sum +a[i];
int avg = sum/a.length;
return avg;
}
}
Where is the problem ? I need to get the average of that array by calling a method that calculate the average.
Change your method call:
average = getAverage(nums);
I see two problems:
average = getAverage(int [] nums) should read average = getAverage(nums).
The function returns an int. You might want to consider using floating-point math for the result. Otherwise you're truncating the answer to the nearest int.
average = getAverage(int [] nums); //this is wrong
average = getAverage(nums); //this is right. Just sintaxis.
avg can be a floating point value, but your implementation will always return integer.
Consider using floating point value for sum and avg and change return type to double.