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

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

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

possible lossy conversion from double to int

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.

Average Random Integers

I am trying to write a program that takes an integer as command-line argument, uses random to print N uniform random values between 0 and 1, and then prints their average value.
I'm not sure what arguments to put in the while loop so that random integers are repeated n times, n being the number from the user indicating the number of integers the random has to generate.
Any help would be appreciated.
enter code here
public class UniformRandomNumbers1 {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int i;
double total = 0.0; //(The sum of n, numbers)
for (i = 1; i <= n; i++) {
double rand = Math.random(); //(Random number between 0 & 1)
total += rand; // Increment total by rand
System.out.println(i + " = " + rand); // Prints value of n & corresponding double value
}
double average = total / n; // Calculates average of n numbers
System.out.println("Average = " + average); // Prints average of n numbers, Can i get an up vote? :) plz
}
}
if you just need to execute a loop a specific number of times, I'd use a for loop
The following loop will iterate exactly n times, and It's what I personally use when I need to do something exactly n times.
for(int i=0; i<n; i++)
{
//insert body here
}
int total = 0;
for (int current = 1; current <= n; n++) {
double rand = Math.random();
total += rand;
System.out.println(currentN + "= " + rand);
}
System.out.println("Total = " + total);
under the assumption that your PRNG is behaving correcly you just need this:
main()
{
printf("\n0.5");
exit(0);
}
that's for N sufficiently large... computed in constant time. otherwise use the moving average formula:
http://en.wikipedia.org/wiki/Moving_average
which requires only O(1) memory space instead of the naive O(N) approach
here the cut&paste java code:
public class Rolling {
private int size;
private double total = 0d;
private int index = 0;
private double samples[];
public Rolling(int size) {
this.size = size;
samples = new double[size];
for (int i = 0; i < size; i++) samples[i] = 0d;
}
public void add(double x) {
total -= samples[index];
samples[index] = x;
total += x;
if (++index == size) index = 0; // cheaper than modulus
}
public double getAverage() {
return total / size;
}
}

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();

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