incompatible types - double to int? - java

Java seems to think that I am attempting to convert or perform some kind of action on one of my double variables. I get the error message
average2.java:23: error: incompatible types: possible lossy
conversion from double to int scores[count++]=score;
I am really confused in that I have not declared anything as an integer thus far, - every variable is a double because I expect to have some decimals. Below is my code :
public static void main (String [] args)
{
double numOf;
double lowest = 100;
double count = 0;
double sum = 0;
double average = 0;
double score;
double scores[] = new double[100]; //[IO.readDouble("Enter Scores, Enter -1 to Quit")];
while ((count <100) &&(( score =IO.readDouble("Enter Scores, (-1 to Quit")) > 0));
{
scores[count++]=score;
}
//This section obtains the highest number that was entered`
double max = scores[0];
for (double i=0; i<scores.length; i++)
if(max < scores[i])max =scores[i];
System.out.println("Maximum is " + max);
// This section obtains the lowest score entered
double min = scores[0];
for (int i=0; i<scores.length; i++)
if (min > scores[i]) min = scores [i];
int sumOf =0;
for (int i=0; i < scores.length; i++)
{
sumOf += scores[i];
}
System.out.println("The sum of all scores is " + sumOf);
System.out.println("Minimum is " + min);
count = count + 1;
average = (sumOf/scores.length);
System.out.println("Average is " + average);
} //end main
} //end class

The error refers to the count variable, which is a double. But ints are valid indices for an array. The error results from using a double as an index where an int was expected for the index.
Declare count to be an int.
You should also declare i to be an int in the first for loop, for the same reason.

Related

How do I cast an int to a double?

The purpose of this program is to intake 5 values (test scores) from the user, then output the average score. I am not familiar with arrays so I really don't have the slightest clue what I'm doing wrong. All I know is the double 'sum' cannot be set equivalent to the int ' total'. Sorry for being dumb but I'M TRYING HERE :)
import java.util.Scanner;
public class Main
{
public static void main (String [] args)
{
int x = 0;
double testScore[] = new double[5];
double sum[] = new double[5];
double total;
int avg;
Scanner keys = new Scanner(System.in);
System.out.println("Enter the values of 5 separate test scores that you have received: \n");
for (int i = 0; i < testScore.length; i++)
{
x++;
System.out.println("Enter your grade for test number " +1);
double score = keys.nextDouble();
score = testScore[i];
sum = testScore;
sum = (int)total;
avg = ((total) / 5);
System.out.print("The sum of your grades is " +avg +"\n");
}
}
}
double sum = 0;
for (double score: testScore) {
sum += score;
}
double avg = sum / testScore.length;
Here you go, I tried not to change much of your code so you can still understand what I changed!
public static void main(String[] args) {
double testScore[] = new double[5];
double sum = 0;
double avg;
Scanner keys = new Scanner(System.in);
System.out.println("Enter the values of 5 separate test scores that you have received: \n");
for (int i = 0; i < testScore.length; i++) {
System.out.println("Enter your grade for test number " + 1);
double score = keys.nextDouble();
sum += score;
avg = sum / 5;
System.out.print("The sum of your grades is " + avg + "\n");
}
}
Basically, all you need is the sum variable, you can get the avg from it!
first i would declare your variables like this:
int x = 0;
double[] testScore = new double[5];
double[] sum = new double[5];
double total;
int avg;
A few changes to be made:
You don't want to set score to testscore[i] because its null so flip that. If you want to cast the doubles to integers use Integer.valueOf(). You should also place them outside the for loop and calculate sum in the for loop, as shown:
for (int i = 0; i < testScore.length; i++)
{
x++;
System.out.println("Enter your grade for test number " +1);
double score = keys.nextDouble();
testScore[i] = score;
sum += Integer.valueOf(score);
total += score;
}
avg = Integer.valueOf(total / testScore.length);
System.out.print("The sum of your grades is " +avg +"\n");
I haven't tested this code but i hope it helps.
In order to get the sum of all elements of an array, you will need to iterate over it:
Scanner keys = new Scanner(System.in);
double[] testScore = new double[5];
double sum = 0.0;
for (int i = 0; i < testScore.length; i++) {
// We don't need to use x, we already have i
System.out.println("Enter your grade for test number " + (i + 1));
double score = keys.nextDouble();
testScore[i] = score; // Store the grade into the element #i of the array
// We can instantly process the data we have to collect. Otherwise we must
// walk a second time over the elements
sum = sum + score; // Or the shorthand notation: sum += score
}
double avg = sum / testScore.length;
System.out.println("The average of your grades is " + avg + "\n");
I modified the following things to your code:
You are using two arrays (testScore and sum) having the same function. Both are meant to store the grades in it. I removed one of them.
I removed x, because i fulfills its function already.
I changed the type of your variable avg to a double. Feel free to change it back to an int, but then the average's decimals will be truncated (for instance, 4.6 will be 4).

Finding the Max Value of the last row of a 2D array

I'm trying to find the maximum value of the last column and i need to print it out. I tried using the Double.max(); method but it doesn't work for the specific array and I wanted to create an array for the 13th column but it won't let me.
import java.lang.reflect.Array;
public class LabMidterm3 {
public static void main(String[] args) {
double[][] myArray =new double [4][13];
double row = myArray.length;
double column = myArray[0].length;
for (int i=0; i<row;i++){
int sum =0;
for(int j=0; j<column;j++){
double random = (int)(Math.random()*7.0);
myArray[i][j] = random;
sum+=myArray[i][j];
System.out.print(myArray[i][j] + ", ");
double max = Array.getDouble(myArray, 13);
if(j==13){
System.out.print("The max value is: " + max);
}
}
double rowAverage= sum/column;
if(i==1){
System.out.println();
System.out.print("The average is: " +rowAverage);
System.out.println();
}
System.out.println();
}
}
Since you are calculating (and storing) double values, don't cast the random to an int. Next, initialize max to some non-present value guaranteed to be smaller than any value present (like -∞). Then use Math.max(double, double) to update it while you iterate the row. And you can use Arrays.toString(double[]) to print your row. Finally, print the average and max after you populate the array. Something like
double sum = 0;
double max = Double.NEGATIVE_INFINITY;
for (int j = 0; j < column; j++) {
myArray[i][j] = Math.random() * 7.0;
max = Math.max(max, myArray[i][j]);
sum += myArray[i][j];
}
System.out.println(Arrays.toString(myArray[i]));
double rowAverage = sum / column;
if (i == 1) {
System.out.println("The average is: " + rowAverage);
System.out.println("The max is: " + max);
}

Create an array based on a range of values given by the user

What I'm trying to do is create an array based on values given by the user. The user has to give the length of the array plus the max and min values. I've managed to get the program to the point where it does output the correct amount of values (the correct length), but it just keeps outputting the exact same number (which is the max and min added). Based on research I did I tried converting them to a string so that wouldn't happen, but it still isn't working correctly. I've tried a couple of different methods including: Integer.toString, String.valueOf, and creating a whole new string. Any help would be greatly appreciated. Here's the code so far:
public static void main(String[] args) {
//Create a Scanner object
Scanner input = new Scanner(System.in);
//Ask the user to enter the length of the array
System.out.println("Please enter the length of the array:");
int arraylength = input.nextInt();
//Ask the user to enter a max value
System.out.println("Please enter the max value:");
int max = input.nextInt();
//Ask the user to input the minimum value
System.out.println("Please enter the min value:");
int min = input.nextInt();
//Initialize the array based on the user's input
double [] userArray = new double[arraylength];
/**
*The program comes up with random numbers based on the length
*entered by the user. The numbers are limited to being between
*the minimum and maximum value.
*/
for (int i = min; i < userArray.length; i++) {
userArray[i] = Math.random() * max;
}
//This code is supposed to sort the array and print out all of the numbers in order,
//with minimum in the beginning and max in the end.
for (int i = 0; i < userArray.length; i++) {
selectionSort(userArray);
Integer.toString(min);
Integer.toString(max);
System.out.println(min + userArray[i] + max);
}
//This code uses the method average to find the average
average(userArray);
//Close Scanner
input.close();
}
public static double average(double[] data) {
double sum = 0;
for (int i = 0; i < data.length; i++) {
sum = sum + data[i];
}
double average = sum / data.length;
return average;
}
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
//Find the minimum in the list[i...list.length-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
//Swap list[i] with list[currentMinIndex] if necessary
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
}
Now, after I added that bit with the average calculation, the program did work once, though it did not compute the average (so it just created an array with min and max at the ends, sorted). It appears to be a fluke, because this is the exact same code and it hasn't done that since. Though maybe the average code somehow affected the rest?
If I understood you problem correctly, you need to change this line
System.out.println(min + userArray[i] + max);
to this:
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
My guess is, that it is java you are using. That tag would be helpful, too.
Edit:
You only need to sort your array once, and these do nothing: Integer.toString(min);
So the print routine could look like this:
selectionSort(userArray);
for (int i = 0; i < userArray.length; i++) {
System.out.println(min.toString() + " " + userArray[i].toString() + " " + max.toString());
}

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.

Number Analysis Program

I am in a beginner Java class and just learning the concept of arrays. We have to use comments to denote the code.
I am trying to make a program that asks the user to enter 20 numbers, stores them in an array and then calculates and displays: the lowest number, the highest number, the total of the numbers and the average of the numbers.
I have a ton of errors when running it through jGrasp and am unsure how to fix them.
Any advice?
public class NumberAnalysisProgram
{
public static void main (String[] args)
{
Scanner input = new Scanner (System.in);
//A constant for the array size
final int SIZE = 20;
//Declare an array to hold the numbers entered by the user
int[] numbers = new int[SIZE];
//Declare variables to hold the lowest and highest
int lowest = numbers[0];
int highest = numbers[0];
//Declare variable to hold the total
int sum;
//Declare a variable to hold the average
double average;
//Declare a counting variable to use in the loops
int index = 0;
//Explain the program
System.out.println("This program gets a list of 20 numbers. Then displays:");
System.out.println(" the lowest number, the highest number, the total of the numbers,
and the average.");
//Get the numbers from the user
for (int i = 0; i< numbers.length; i++)
{
System.out.print("Please enter 20 numbers, each seperated by a space: ");
numbers[i] = input.nextInt();
}
//Call a method to calculate the lowest and highest numbers
getLowHigh(numbers);
//Display the lowest and highest numbers
System.out.println("The lowest number is: " + lowest);
System.out.println("The highest number is: " + highest);
//Call a method to calculate the total of the numbers
sum = getTotal(numbers);
//Display the sum/total of the numbers
System.out.println("The total of these numbers are: " + sum);
//Call a method to calculate the average of the numbers
average = getAverage(sum, numbers);
//Display the average of the numbers
System.out.println("The average of these numbers are: " + average);
}
//Method getLowHigh
public static int getLowest(int[] array)
{
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > highest)
highest = numbers[i];
else if (numbers[i] < lowest)
lowest = numbers [i];
}
return highest;
return lowest;
}
//Method getTotal
public static int getTotal(int[] array)
{
//Loop counter variable
int index;
//Accumulator variable initialized to 0
int total = 0;
//Pull in the numbers from the main method to calculate the total
for(index = 0; index < numbers.length; index++)
{
total = total + number[index];
}
return total;
}
//Method getAverage
public static int getAverage(int[] array)
{
//Loop counter variable
int index;
//Pull in the sum and the numbers from the main method to calculate the average
for(index = 0; index < numbers.length; index++)
{
average = sum / number[index];
}
return average;
}
}
The first problem I can see is that in all of the methods, you never used the arguments. You used a different array, which doesn't exist within those methods.
The second problem is that you're trying to return two values from one method. You can only return one value from a method. So you have to get rid of "return highest;" and make a copy of the method in which there is no "return lowest;", and use each where needed.
The third thing I see (although it isn't causing any errors) is that you could shorten the code by saying
int total = 0;
for(int index = 0; index < numbers.length; index++)
{
total += number[index];
}
instead of
int index;
int total = 0;
for(index = 0; index < numbers.length; index++)
{
total = total + number[index];
}
For starters, the below code is trying to initialize variables to array values that don't exist… These should be removed entirely.
//Declare variables to hold the lowest and highest
int lowest = numbers[0];
int highest = numbers[0];
There will also be an error with these in the code below because you're not passing them to the function therefore it doesn't exist within this scope.
public static int getLowest(int[] array)
{
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > highest)
highest = numbers[i];
else if (numbers[i] < lowest)
lowest = numbers [i];
}
return highest;
return lowest;
}
You are also supplying 2 parameters for a function that only calls for one. See below:
//Call a method to calculate the average of the numbers
average = getAverage(sum, numbers);
public static int getLowest(int[] array)
{
for(int i=1; i< numbers.length; i++)
{
if(numbers[i] > highest)
highest = numbers[i];
else if (numbers[i] < lowest)
lowest = numbers [i];
}
return highest;
return lowest;
}
I think that this is more clean:
public class Main {
public static final int SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Integer> numbers = new ArrayList<Integer>();
Double total = 0d;
System.out.println("This program gets a list of 20 numbers. Then displays:");
System.out.println(" the lowest number, the highest number, the total of the numbers, and the average.");
// Get the numbers from the user
System.out.print("Please enter 20 numbers, each seperated by a space: ");
for (int i = 0; i < SIZE; i++) {
Integer currInput = input.nextInt();
numbers.add(currInput);
total += currInput;
}
System.out.println("The lowest number is: " + Collections.min(numbers));
System.out.println("The highest number is: " + Collections.max(numbers));
System.out.println("The total of these numbers are: " + total);
System.out.println("The average of these numbers are: " + (total / SIZE));
}
}
Hope it helps :]

Categories