possible lossy conversion from double to int - java

Write a program that contains two overloaded methods that return the average of an array with the following headers:
public static int average(int[] array)
public static double average(double[] array)
my program contains the errors
list2[i] = sc.nextDouble(); // possible lossy conversion from double to int
return average; // possible lossy conversion from double to int
not sure what the problem is I have declared within my methods what needs to be declared I don't know why my double in put would give me that error
import java.util.Scanner;
public class Lab7A {
public static void Main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter 10 Integer values: ");
int list[] = new int[10];
for (int i = 0; i < list.length; i++) {
list[i] = sc.nextInt();
}
double avg1 = average(list);
System.out.println("Average of First Array: " + avg1);
System.out.println();
System.out.print("Enter Ten Double Values: ");
double list2[] = new double[10];
for (double i = 0; i < list2.length; i++) {
list2[i] = sc.nextDouble();
}
double avg2 = average(list2);
System.out.println("Average of Second Array: " + avg2);
System.out.println();
}
public static int average(int[] list) {
double average = 0;
double total = 0;
for (int i = 0; i < list.length; i++) {
total = total + list[i];
}
average = total / list.length;
return average;
}
public static double average(double[] list2) {
double average = 0;
double total = 0;
for (int i = 0; i < list2.length; i++) {
total = total + list2[i];
}
average = total / list2.length;
return average;
}
}

Your average(double[]) method is attempting to use a double as an array index, but Java only allows ints as an array index. This is the source of the "possible lossy conversion from double to int".
Everything else is and should be double, but declare your index d as int to remove this error.
Additionally, in the for loop of that method, the condition should be d < list2.length instead of d < 5.
Also, the average of int values may not necessarily be an int. In your average(int[]) method, declare it to return a double, and declare average to be a double. The variable avg1 will need to be a double in main also.

Related

How to separate my code into different methods

So I have an assignment where i'm supposed to create a program that generates 100 random integers and stores them in a single dimensional array. I am then supposed to calculate the average, standard deviation and variance. Through a lot of trial and error I was able to make a program that did this but what I missed was that it said to write a separate method for each property(average, standard deviation and variance). How would i go about doing that?
package homeassignment5;
public class HomeAssignment5 {
public static void main(String[] args) {
int n;
n = 100;
int[] random = new int [n];
for (int i = 0; i<random.length; i++)
random[i] = (int) (Math.random()* n);
double total = 0;
double average = 0;
double variance = 0;
double var = 0;
double sd = 0;
for (int element : random){
total += element;
average = total/n;
}
for (int i = 0; i<random.length; i++){
variance += (random[i] - average) * (random[i] - average);
}
var = variance / random.length;
sd = Math.sqrt(var);
//System.out.println("Total is: " + total);
System.out.println("Average is: " + average);
System.out.println("Variance is " + var);
System.out.println("Standard deviation is " + sd);
/*for (int i = 0; i<random.length; i++)
System.out.println(random[i]);
*/
}
}
Might be a bit of a mess but i'm really new to java and this was the product of a ton of trial and error.
So there are several ways of going about this, but the easiest would probably be this:
public class HomeAssignment5 {
private static int[] random;
public static void main(String[] args){
random = = new int[100];
...
}
public static void getAverage(){
// void if you want to print it here, double if you want to print in main
double average = 0;
int total = 0;
for(int i = 0; i < 100; i += 1)
total += random[i];
average = total / n; // you'll want to do this outside of the loop to
// to get the correct result!
System.out.println("Average: " + average);
}
...
}
You could alternatively pass the array to each method as a parameter.
By the way, in what you posted here, you still haven't actually written any random numbers into the array, so remember to do that, it's currently still all zero.
I believe this should help you..
All the functionalities are separated in form of methods,
the initialization is separated.
** WELCOME TO REFACTORING **
public class Refactor {
private int[] random;
private int n;
private double total = 0;
private double average = 0;
private double variance = 0;
private double sd = 0;
public Refactor(int n) {
this.n = n;
this.populateArray();
}
private void populateArray() {
random = new int[n];
for (int i = 0; i < random.length; i++)
random[i] = (int) (Math.random() * n);
}
public double getAverage() {
average = 0;
total = 0;
for (int element : random) {
total += element;
}
average = total / n;
return average;
}
public double getVariance() {
variance = 0;
for (int i = 0; i < random.length; i++) {
variance += (random[i] - average) * (random[i] - average);
}
variance = variance / random.length;
return variance;
}
public double getSD() {
this.getVariance();
sd = 0;
sd = Math.sqrt(variance);
return sd;
}
public static void main(String[] args) {
Refactor ref = new Refactor(100);
System.out.println("Average is: " + ref.getAverage());
System.out.println("Variance is " + ref.getVariance());
System.out.println("Standard deviation is " + ref.getSD());
}
}
How would i go about passing the array to each method?
The first and most straightforward of the three methods is average:
static double average(int [] r)
{ double total = 0;
for (int e: r) total += e;
return total/r.length;
}
For the second method, the standard deviation, I recommend not to pass the array, but rather the variance, since if the program has calculated the variance anyway, it need not be recalculated, and if it doesn't have, the SD method can be called with a call to the variance method as its argument.
static double SD(double variance) { return Math.sqrt(variance); }
For the third method, the variance, I recommend not only to pass the array, but also its average, with similar reasoning as above.
static double variance(int [] r, double average)
{ double var = 0;
for (int e: r) var += (e - average) * (e - average);
return var/r.length;
}
With those three methods defined, you can now replace
double total = 0;
double average = 0;
double variance = 0;
double var = 0;
double sd = 0;
for (int element : random){
total += element;
average = total/n;
}
for (int i = 0; i<random.length; i++){
variance += (random[i] - average) * (random[i] - average);
}
var = variance / random.length;
sd = Math.sqrt(var);
with
double average = average(random);
double var = variance(random, average);
double sd = SD(var);

Incompatible types: double[][] can not be converted to double

I am trying to resolve an issue for this assignment I was given for Homework. I am currently stuck and would appreciate any help that could guide me in correcting the program.
The original assignment is as follows:
Write a program that uses a two-dimensional array to store the highest and lowest temperatures for each month of the year. Write two methods : one to calculate and return the average high and one to calculate and return the average low of the year. Your program should output all the values in the array and then output the average high and the average low.
This is the code I have assembled so far and have an error that I am not able to resolve. It is " incompatible types: converting double[][] cannot be converted to double. The lines in question are Line 8, and Line 110 ( the last return in the program).
import java.util.*;
public class Weather
{
public static void main(String[] args)
{
double[][] tempData = getData();
printTempData(tempData);
double avgHigh = averageHigh(tempData);
double avgLow = averageLow(tempData);
int indexHigh = indexHighTemp(tempData);
int indexLow= indexLowTemp(tempData);
System.out.format("The average high temperature is %4.1f%n", avgHigh);
System.out.format("The average low temperature is %4.1f%n", avgLow);
System.out.format("The index of high temperature is %2d%n", indexHigh);
System.out.format("The index of low temperature is %2d%n", indexLow);
}
private static void printTempData(double[][] tempData)
{
System.out.format("%6s:%4s%4s%4s%4s%4s%4s%4s%4s%4s%4s%4s%4s%n","Month","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
System.out.format("%6s:","Low");
for (int i = 0; i < tempData[0].length;i++)
{
System.out.format("%4.1s", tempData[0][i]);
}
System.out.format("%n");
System.out.format("%6s: ","High");
for (int i = 0; i < tempData[1].length; i++)
{
System.out.format("%4.1f", tempData[1][i]);
}
System.out.format("%n");
}
private static int indexLowTemp(double[][] tempData)
{
int index = 0;
double temp = tempData[0][0];
for (int i = 0; i < tempData[0].length; i++)
{
if (temp > tempData[0][i])
{
temp = tempData[0][i];
index = i;
}
}
return index +1;
}
private static int indexHighTemp(double[][] tempData)
{
int index = 0;
double temp = tempData[1][0];
for(int i = 0; i< tempData[1].length; i++)
{
if ( temp < tempData[1][i])
{
temp = tempData[1][i];
index = i;
}
}
return index + 1;
}
private static double averageHigh(double[][] tempData)
{
double avg = 0.0;
for(int i=0; i < tempData[0].length; i++)
{
avg += tempData[0][i];
}
avg /= tempData[0].length;
return avg;
}
private static double averageLow(double[][] tempData)
{
double avg = 0.0;
for(int i=0; i > tempData[1].length; i++)
{
avg += tempData[0][i];
}
avg /= tempData[0].length;
return avg;
}
private static double getData()
{
double[][] tempData = new double[2][12];
Random r = new Random();
for (int j = 0; j < tempData[0].length; j++)
{
tempData[0][j] = 30 + Math.sqrt(j) - r.nextDouble();
tempData[1][j] = 30 + Math.sqrt(j) + r.nextDouble();
}
return tempData;
}
}
Your method private static double getData() should be private static double[][] getData()
You already declared an array
double[][] tempData = getData();
but you are trying to call
private static double getData()
thus the error "converting double[][] cannot be converted to double."
Hence change to
private static double[][] getData()
The method should be private static double[][] getData()

Standard Deviation java, proper equation

This is all my code. I am having problems with the standard deviation formula.
I run the program with these values:
Number of items: 5
Items: 16 25 81 80 24
I'm supposed to get this output:
Average:    45.20
Std Dev:    32.41
Less than Avg: 3
Array is not in sorted order
Instead, I get this output:
Array is not in sorted order
Average: 45.20
Std Dev: 55.60
Less than Avg: 3
import java.text.DecimalFormat;
import java.util.Scanner;
public class array {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat df = new DecimalFormat ("#.00");
System.out.println("How many values do you want?");
int num = input.nextInt();
if (num< 1 || num > 100)
{
System.out.println("Error");
System.exit(0);
}
int[] array= valueArray(input, num);
double o= average(num, array);
double standdev = getStdDev(array, num);
int lessThanAvg = lessAvg ( array, num, o );
boolean sorted=isArraySorted(array, num);
System.out.println("Average: " + df.format(o));
System.out.println("Std Dev: " + df.format(standdev));
System.out.println("Less than Avg: " + lessThanAvg);
}
public static int[] valueArray (Scanner input, int num )
{
int[] values = new int[100];
System.out.println("What numbers do you want to put in?");
for (int j = 0; j < num; j++)
{
values[j]=input.nextInt();
}
return values;
}
public static double average ( int num ,int[] values)
{
double avg=0.0;
for (int i = 0; i < num; i++)
{
avg = avg+values[i];
}
return avg/num;
}
public static double getStdDev (int [] values, int num)
{
double avg = 0.0;
double sum = 0 ;
for (int i = 0; i < num - 1; i++)
{
sum = Math.sqrt ((Math.pow((values[i]-avg),2) + Math.pow((values[num-1]),2)) / num-1);
}
return sum;
}
public static int lessAvg ( int [] values, int num, double avg )
{
int counter = 0;
for (int i = 0; i < num; i++ )
{
if (values[i] < avg)
{
counter = counter + 1;
}
}
return counter;
}
public static boolean isArraySorted (int [] values, int num)
{
for (int i = 0; i < num - 2; i++)
{
if (values[i]>values[i+1])
{
System.out.println("Array is not in sorted order");
return false;
}
}
System.out.println("Array is in sorted order");
return true;
}
}
to get the standard deviation
find out the mean.
Then for each number of your array subtract the Mean and square the
result.
Then work out the mean of those squared differences
find the square root of that.
For reference you can look at this Post

Integer to Double variable

I need to create a program that will prompt the user to enter salaries and get the highest and lowest salaries.. Ive been working on it for 4 days now.. and I finally created my program using some of the tutorials on the internet but I only have one problem... I just can't convert the INT to Double ## its giving me a headache.. where did I go wrong? can someone help me? I need to pass java class ;;
here's the code:
import java.util.*;
public class HighestLowestSalary
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("How many salary do you want to enter?: ");
int sal = input.nextInt();
//starting here should be double already..
System.out.println("Enter the "+sal +" salaries");
int[]salary = new int[sal];
for (int i=0; i<sal; i++)
{
salary[i]=input.nextInt();
}
System.out.println("The Highest Salary is: " +high(salary));
System.out.println("The Lowest Salary is: " +low(salary));
}
public static int high(int[] numbers)
{
int highsal = numbers[0];
for (int i=1; i<numbers.length;i++){
if (numbers[i] > highsal){
highsal = numbers[i];
}
}
return highsal;
}
public static int low(int[] numbers){
int lowsal = numbers[0];
for (int i=1;i<numbers.length;i++){
if (numbers[i] < lowsal){
lowsal = numbers[i];
}
}
return lowsal;
}
}
anyone who can help me and teach me how to convert it in double? thank you in advance..
Erm ... to convert an int to a double you can just assign it. The assignment will cause a a "primitive widening conversion" to occur; see JLS 5.1.2.
int myInt = 42;
double myDouble = myInt; // converts to a double.
(No typecast is necessary for a primitive widening conversion ... though adding one does not harm.)
To convert an int array to a double array ....
int[] myInts = ....
double[] myDoubles = new double[myInts.length];
for (int i = 0; i < myInts.length; i++) {
myDoubles[i] = myInts[i];
}
You could just assign an int value to double like:
int n = 1;
double j = n;
System.out.println(j);
Output:
1.0
Note: you could ask for salary to be of double type by using nextDouble api instead of nextInt
I was able to solve the problem because of your help! here is what I did.. like everyone said to convert int to Double
//this is where I changed all the int to double
System.out.println("Enter the "+sal +" salaries");
double[]salary = new double[sal];
for (int i = 0; i<sal; i++){
salary[i] = input.nextDouble();
}
System.out.println("The Highest Salary is: " +high(salary));
System.out.println("The Lowest Salary is: " +low(salary));
}
public static double high(double[] numbers)
{
double highsal = numbers[0];
for (int i=1; i<numbers.length;i++){
if (numbers[i] > highsal){
highsal = numbers[i];
}
}
return highsal;
}
public static double low(double[] numbers){
double lowsal = numbers[0];
for (int i=1;i<numbers.length;i++){
if (numbers[i] < lowsal){
lowsal = numbers[i];
}
}
return lowsal;
}
}

Not ignoring a value?

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.

Categories