How do I cast an int to a double? - java

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).

Related

Why is it not allowing me to input just 5 numbers, when I run it, it allows me to input 6

import java.util.Scanner;
public class Lab11d
{
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
double [] anArray; // declares an array of integers
anArray = new double [5];
int min=0;
//Initalizes the array values//
System.out.println ("Enter 5 numbers of your choosing");
double a = in.nextDouble();
for ( int count=0; count < 5; count++)
{
anArray[count] = a;
a = in.nextDouble();
}
//Prints array values//
for (double value : anArray)
System.out.println ("Element at index " + (min++) + ":"+ value + "" );
}
}
It runs, but I only want to input 5 numbers, not sure what I am doing wrong. It allows me to enter six with like a limit of 5, curious how to change it please
Because you get one double before your loop. Change it to something like
// double a = in.nextDouble();
for (int count=0; count < 5; count++)
{
double a = in.nextDouble();
anArray[count] = a;
}
or eliminate a altogether like
for (int count=0; count < 5; count++)
{
anArray[count] = in.nextDouble();
}
You are accepting a double first time and then iterating through a loop which accepts 5 doubles i.e. in total you are accepting 6 doubles.
You have to edit your for loop as,
for ( int count=0; count < 5; count++)
{
anArray[count] = in.nextDouble();
}

incompatible types - double to int?

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.

Need aid with the code I wrote (need to understand)

The code below is what I have wrote for my assignment for class.
I have not learned from the instructor yet about the arrays, and
data. I have understood how to use the arrays, but not quite sure
about the data yet.
I have marked where I need help for the code below.
Although I have managed to write it, still not sure if it is optimal.
Could someone help me to better it perhaps?
*I asked previously about finding the mode, and people told me to do it with the
map implementation, I tried to do it, but my brain won't work for it.. any suggestions?
=================================================================================
import java.util.Scanner;
import java.util.Arrays;
public class CodeVer2 {
public static void main(String[] args)
{
Double num1, num2, num3, num4, num5, sum, avg;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the first number:");
num1 = keyboard.nextDouble();
System.out.println("Enter the seond number:");
num2 = keyboard.nextDouble();
System.out.println("Enter the third number:");
num3 = keyboard.nextDouble();
System.out.println("Enter the fourth number:");
num4 = keyboard.nextDouble();
System.out.println("Enter the fifth number:");
num5 = keyboard.nextDouble();
keyboard.close();
double[] num = new double[5]; // array named num is declared with 5 variables
num[0] = num1;
num[1] = num2;
num[2] = num3;
num[3] = num4;
num[4] = num5;
Arrays.sort(num);
double[] data = {num1, num2, num3, num4, num5}; // I need help from here,
int mode = 0;
int[] index = new int[999];
int maximum = Integer.MIN_VALUE;
for (int i = 0; i < data.length; i++){
index[(int) data[i]]++;
}
for (int i = 0; i < index.length; i++){
if(maximum < index[i]){
maximum = index[i];
mode = i;
}
} // to here.
sum = num[0] + num[1] + num[2] + num[3] + num[4];
avg = sum/5;
System.out.println(" ");
System.out.println("Sum:" + sum);
System.out.println("Avg:" + avg);
System.out.println("Max:" + num[4]);
System.out.println("Min:" + num[0]);
System.out.println("Median:" + num[2]);
System.out.println("Mode:" + mode);
}
}
So all double[] does is set up an array that can contain 0 or more numbers. Think of it like a sheet of paper with a row of boxes on it. You can't add more boxes or take them away but you can write a different number in each box.
double[] data = {num1, num2, num3, num4, num5}; // I need help from here,
This creates a row of boxes, and writes the numbers in the { } into the row. It automatically creates the row to be the right size to hold the things in the brackets.
int mode = 0;
int[] index = new int[999];
int maximum = Integer.MIN_VALUE;
This creates a new list of boxes, these ones can each hold an integer and there are 999 of them.
for (int i = 0; i < data.length; i++){
index[(int) data[i]]++;
}
This loops through your data. data[i] says "use the value in the box numbered i, counting from the start of the boxes with the first box being 0".
It converts that double value to an integer and then looks up the box corresponding to that integer. It adds one to the value at that position. Note that there is a flaw in the algorithm here, if someone puts in a number over 999 then you won't have enough boxes.
for (int i = 0; i < index.length; i++){
if(maximum < index[i]){
maximum = index[i];
mode = i;
}
}
Now this loops through every box in the index array. Since earlier values are over-ridden and since you never actually calculate the maximum it actually just gives you the value in box 999 of the array and sets mode to 999. That doesn't sound very useful...
first of all I rewrote your code to make it easier to read.
What is missing is: what does this "mode" mean. I couldn't derive it from your code.
The code below is not perfect. A lot of error handling and boundary checking is missing. I leave that as an exercise for you.
So, try to understand what my code does. Think about the meaning of "mode" and how to calculate it.
import java.util.Scanner;
import java.util.Arrays;
public class CodeVer2 {
static final String CARDNAME[] = { "first", "second", "third", "fourth", "fifth" };
static final int NUM_ITEMS = 5;
public static void main(String[] args)
{
double num[], sum, avg, max, min;
double mode = 0.0; // don't know what this is
int i;
num = new double[NUM_ITEMS];
sum = 0;
max = Double.NEGATIVE_INFINITY;
min = Double.POSITIVE_INFINITY;
Scanner keyboard = new Scanner(System.in);
for (i = 0; i < NUM_ITEMS; ++i) {
System.out.println("Enter the " + CARDNAME[i] + " number:");
num[i] = keyboard.nextDouble();
sum += num[i];
if (max < num[i]) max = num[i];
if (min > num[i]) min = num[i];
}
avg = sum / NUM_ITEMS;
Arrays.sort(num);
keyboard.close();
System.out.println(" ");
System.out.println("Sum:" + sum);
System.out.println("Avg:" + avg);
System.out.println("Max:" + max);
System.out.println("Min:" + min);
System.out.println("Median:" + num[NUM_ITEMS/2]);
System.out.println("Mode:" + mode);
}
}

Editing exception e to catch letters not decimals

I'm writing a program that takes 10 floating point numbers as input. However, whenever I enter a decimal the program sends me an error. I question is: how would I edit my current try-catch exception to catch only letters, etc., and allow decimals to be entered (and then store them into an array). Also, regardless of this problem, my program is also outputting the average many times, and always saying that it is equal to 0.
Below is the program:
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
new Average().average(new double[10]);
}
public double average(double[] number) {
Scanner scanner = new Scanner(System.in);
int x = 0;
double sum = 0;
double[] numberList = new double[10]; //array to hold all numbers
double[] largerList = new double[10]; //array to hold numbers greater than the average
int numberIndex = 0;
int largerIndex = 0;
System.out.printf("Please enter 10 floating-point numberes.\nIf more than 10 values are entered, the numbers following 10 are ignored.\nIf less than 10 numbers are entered, the program will wait for you to enter 10.\n");
for (int i = 0; i < 10; i++) {
try { //try catch exception to catch decimal inputs as well as more /less than 10 integers
x = scanner.nextInt();
sum += numberList[x]; //add up all inputs to find sum
} catch (Exception e) {
System.out.println("Invalid input! Please reenter 10 integer values.");
scanner = new Scanner(System.in);
i = -1;
numberIndex = 0;
largerIndex = 0;
numberList = new double[10];
largerList = new double[10];
continue;
}
}
for (int i = 0; i < number.length; i++) {
sum = sum + number[i];
double average = sum / number.length;
//return average;
if (x > average) {
largerList[largerIndex] = x; //add negative input to negativeList array
largerIndex = largerIndex + 1;
}
System.out.println("Average value of your input is: " + average);
System.out.println();
}
for (int i = 0; i < largerIndex; i++) {
System.out.println(largerList[i]);
}
return 0;
}
}
You're using the nextInt() function, which only returns ints. Ints cannot hold decimals. Consult the API and take a look at the nextFloat() and nextDouble() methods instead.
For your Average problem, Your print statement is into a for loop so it will be executed number.length times. Move the print statements outside the loop. You will also need the declaration of the average variable to be outside the loop. Also you should only need to the loop to calculate the sum, you don't need the calculate the average everytime
double average;
for(/*loop conditions*/)
{
sum = sum + number[i];
}
average = sum / number.length;
System.out.println("Average value of your input is: " + average);
System.out.println();

Finding the average of a column in a matrix with unknown elements

Can anyone help me with my code? I have to find the average of every column in a matrix but I don't know what's wrong with my code cause it doesn't work.This is my code: (By the way it shows no mistakes and I had to put the numbers with JOptionPane, thanks for your help)
import javax.swing.JOptionPane;
public class Matrix {
private static final int String = 0;
public static void main(String[] args) {
double[] numbers = new double[10]; // 10 doubles
double sum = 0.0;
for (int i = 0; i < numbers.length; ++i) {
sum += numbers[i];
String input = JOptionPane.showInputDialog("Enter a number");
double d = Double.parseDouble(input);
double avg = 0.0;
avg = sum/numbers[i];
}
}
}
You never assign any numbers to your numbers array, so they all default to 0.
Try:
numbers[i] = Double.parseDouble(input);
double avg = 0.0;
sum += numbers[i];
avg = sum / (i + 1); // (i + 1) is the number of inputted numbers

Categories