Calculating average: Converting Double to String Error - java

I just can't get my code right how I want to. (Java Beginner)
So the way it should work is this:
When running the program I want to get a window and fill in a number(X) how large(Z) the array should be. Next I get X windows where I have to type in the numbers I want to put in the array. Finally the program should calculate the sum of all numbers and divide by the size(Z) of the array, to get the average of all numbers in the array.
I'm almost finished but all I get are errors regarding Double to String conversion. I tried everything I know out but couldn't make it work. Please excuse there may be spelling mistakes, I had to translate it to english.
Error:
Below //Initialization and Output line, either it's 'void' type not allowed here or incompatible types: void cannot be converted to String
import javax.swing.*;
import java.util.*;
public class Aufgabe42
{
public static void main(String[] args)
{
//Declare variable
String input, output, requestNumber;
double[] arrayNumber;
int size;
//Input
input = JOptionPane.showInputDialog(null, "Type in the size of the array.");
//Variable Initialization
size = Integer.parseInt(input);
arrayNumbers = new double[size];
//Request numbers
for(int i = 0; i < size; i++)
{
requestNumber = JOptionPane.showInputDialog(null, "Tell me a number:");
arrayNumber[i] = Double.parseDouble(requestNumber);
}
String returnAverage;
//Initialization and Output
output = Double.toString(JOptionPane.showMessageDialog(null, "The Average is: " + getAverage(arrayNumber)));
System.exit(0);
}
public static double getAverage(double[] arrayNumber)
{
//Declare variable
double arraySum,average;
//Initialization
arraySum = 0;
returnAverage = Double.toString(average);
//Sum array values
for(int i = 0; i < arrayZNumber.length; i++)
{
arraySum += arrayNumber[i];
}
//Calculate Average
average = arraySum / arrayNumber.length;
return average;
}
}

JOptionPane.showMessageDialog()
Has a void return type. You either want
JOptionPane.showInputDialog()
Or to remove
Double output = Double.valueOf(JOptionPane.showMessageDialog...)
near the end
https://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html

Related

How do i stop program from running until user is finished inputting?

I want the user to be able to input the amount of numbers they specified BEFORE the code keeps running. Currently, the user is only able to input one number before the code continues. How do i keep the code from running until a certain amount of numbers are inputted?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n;
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter the amount of numbers you want the array to store: ");
// reads # of # user wants to enter
n = sc.nextInt();
// creates an array in the memory of length 10
int[] array = new int[10];
System.out.println("Enter "+n+" numbers ");
for (int i = 0; i < n; i++) {
// reading array elements from the user
array[i] = sc.nextInt();
double sum = 0;
double mode = 0;
double variance = 0;
double deviation = 0;
for (i = 0; i < 2; i++)
sum = sum + array[i];
//MEAN
mode = sum / 5;
sum = 0;
for (i = 0; i < 2; i++) {
sum = sum + Math.pow((array[i] - mode), 2);
}
//VARIANCE
variance = sum / 5;
//DEVIATION
deviation = Math.sqrt(variance);
//Standard
System.out.println("Standard Deviation is: " + deviation);
//mode
System.out.println("Mode is:" + mode);
//Variance
System.out.println("Variance is: " + variance);
}
}
}
I tried to let the user decide how many numbers should be in the array, then input that many numbers.
However, when i run the code, it doesn't give them enough time to type in the numbers.
I need a way to stop this from happening.
The first thing I discovered is that at no time are you using the variable "n" to create a constant value array, so it will always be an array of 10 elements.
One recommendation that I give you is that you do not use the "Scanner" class because it can give you problems if you ask the user for different types of data. Instead it uses BufferedReader because it is more direct. Here is an example of your exercise but fixed:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Main {
private static Number getNumber(BufferedReader reader) throws IOException {
// Get input content
String line = reader.readLine();
return Double.parseDouble(line);
}
public static void main(String[] args) throws IOException {
// Auto closeable elements
try (InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader buffered = new BufferedReader(reader)) {
// Print message
System.out.print("The amount of numbers you want: ");
// Program variables here
final int totalSize = getNumber(buffered).intValue();
int[] arrayStore = new int[totalSize];
// Iterate all elementos of the array
for (int i = 0; i < totalSize; ++i) {
// Another message
System.out.print("Insert one number: ");
// Ask for numbers
int nextNumber = getNumber(buffered).intValue();
arrayStore[i] = nextNumber;
}
// TODO: Your logic program here
System.out.println(Arrays.toString(arrayStore));
}
}
}
If you were able to notice, the method that asks for the numbers does not check if the content is really a number, for that change the behavior of the getNumber method to the following:
private static Number getNumber(BufferedReader reader) throws IOException {
Number result = null;
do {
try {
result = Double.parseDouble(reader.readLine());
} catch (NumberFormatException e) {
System.err.println("The inserted content is not a valid number");
}
} while (result == null);
return result;
}
I hope it helps you in some way

Can't enter loop with int but only using final int

I've created this class in a separate file and the program runs. The questions I have is the for a loop. Currently, I'm using a final int. I wanted to input a variable for
ol < MAX_R
} // End input loop
// Added feature that is not part of grading
System.out.print("Press enter to see results: ");
try {
System.in.read();
} catch (Exception e) {
e.printStackTrace();
}
Well, I think that author wants to read round scores for input stream and calculate an average. This is pretty simple, I think. First, you have to split your method into required logical parts: read data from stream, data processing, output data (to make your code simple and clear).
Java is not a C++. Here you can define array size wherever you like, as well as using user's input at runtime (Java does not require to know size of array at compile time).
public class Foo {
public static void main(String... args) {
double[] scores = readRoundScores();
double avg = calcAverageScore(scores);
System.out.println("\nAverage score: " + avg);
}
private static double[] readRoundScores() {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter total rounds: ");
double[] scores = new double[scan.nextInt()];
for (int i = 0; i < scores.length; i++) {
System.out.printf("Enter your round %d score: ", i + 1);
scores[i] = scan.nextDouble();
}
return scores;
}
}
private static double calcAverageScore(double... scores) {
double sum = 0;
for (double score : scores)
sum += score;
return sum / scores.length;
}
}

using scanner class to average numbers in java

I am using a scanner class to average numbers together. I am using a method to do the averaging. I do not want the program to run if there are more than 20 args. I cant seem to get this to work. I am very new at java and trying to learn.
I appreciate any help I can get. Thanks!
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double x = 0.00d;
if (args != null) {
System.out.println ("Enter your numbers to be averaged. Remember no more than 20!:");
x = scan.nextInt();
if (x <= 21) {
System.out.println("Please do not add more than 20 numbers");
}
} else {
}
}
public double average(double [] values) {
double average = 0.0;
if ((values != null) && (values.length > 0)) {
for (double value : values) {
average += value;
}
average /= values.length;
}
return average;
}
}
Just run a while loop that breaks when 20 "args" is met or until a break like -1 is entered. Then if you are taking double values, you should use x = scan.nextDouble(). You also do not have a place where you are inserting the values into your array. At the end of your while loop you could put x into an array of doubles.
private double x;
private double Foo[] = new Foo[20];
private int this = 0; //Your counter
while(this < 20 && x != -1)
{
x = scan.nextDouble();
Foo[this++] = x;
}
Then carry out your public double Average by adding up the values in the array and dividing by (double)this
Here is a solution (cleaning up a lot of your code as well) that gets all the numbers on one line after the start of the program:
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double values[] = new double[20];
int count = 0;
System.out.println ("Enter your numbers to be averaged. Remember no more than 20!:");
String inputs = scan.nextLine();
scan = new Scanner(inputs); // create a new scanner out of our single line of input
while(scan.hasNextDouble())
{
if(count == 20)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
values[count] = scan.nextDouble();
count += 1;
}
System.out.println("Your average is: " + average(values, count));
}
public static double average(double [] values, int count) {
double average = 0.0;
for (double value : values) {
average += value;
}
average /= count;
return average;
}
}
I got thinking you might want to use the args that are passed to main, since you use a null check, so you want to run your program like this:
java programTwo num1 num2 num3 num4 num5
etc. If that's the case, we have another solution:
class programTwo {
public static void main (String[] args) {
if(args.length > 20)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
double values[] = new double[args.length];
for(int i=0; i< args.length; ++i)
values[i] = Double.valueOf(args[i]);
System.out.println("Your average is: " + average(values));
}
public static double average(double [] values) {
double average = 0.0;
for (double value : values) {
average += value;
}
average /= values.length;
return average;
}
}
The args != null check is unnecessary. One way to accomplish what you want is to accept numbers while the scanner has a next number (scanner.hasNext() perhaps) and break if the number of inputs thus far is less than 20. Since the number of double numbers is unknown, you're better off using an ArrayList.
List<Double> doubles = new ArrayList<Double>();
and calling the add method on doubles
doubles.add(x);
Then pass this to a method that averages the values in the arraylist.

Computing the average of an array

This is a code to take user imputed grades, find their average, the deviation, and display this information in a table style. My program takes user input and displays the information well, but it won't compute the average and the deviation properly. When run, it says the average is 0. I'm doing it the same why my teacher taught us, but I can't find my error.
import java.util.Scanner;
public class ClassScores{
public static void main(String[] args){
String[] names = {"Bashful","Doc","Dopey","Grumpy","Happy","Sleepy","Sneezy"};
double[] grades = new double[7];
double mean=0;
double[] difference = new double[7];
getScores(grades);
average(grades, mean);
deviation(grades,mean,difference);
displayResults(names, grades, difference, mean);
}
public static double[] getScores(double[] grades)
{
Scanner kb= new Scanner(System.in);
System.out.println("Enter grades for students in alphabetical order.");
for (int i=0;i<grades.length; i++)
{
grades[i]=kb.nextDouble();
}
return grades;
}
public static double average(double[] grades, double mean)
{
double total = 0;
for (double i : grades)
{
total += i;
}
if (grades.length>0)
{
mean = total/grades.length;
}
return mean;
}
public static double[] deviation(double[] grades, double mean, double[] difference)
{
for (int i=0; i<grades.length; i++)
{
difference[i]=grades[i]-mean;
}
return difference;
}
public static void displayResults(String[] names, double[] grades, double[] difference, double mean)
{
System.out.println("The average score is" +mean);
System.out.println("Student Name Grade Mean Deviation");
for (int i=0; i<names.length; i++)
{
System.out.printf(names[i]);
System.out.printf("%20f", grades[i]);
System.out.printf("%20f", difference[i]);
System.out.println();
}
}
}
Here is the edited code for anyone who's curious.
import java.util.Scanner;
public class ClassScores{
public static void main(String[] args){
String[] names = {"Bashful","Doc","Dopey","Grumpy","Happy","Sleepy","Sneezy"};
double[] grades = new double[7];
double mean=0;
double[] difference = new double[7];
getScores(grades);
mean = average(grades);
deviation(grades,mean,difference);
displayResults(names, grades, difference, mean);
}
public static double[] getScores(double[] grades)
{
Scanner kb= new Scanner(System.in);
System.out.println("Enter grades for students in alphabetical order.");
for (int i=0;i<grades.length; i++)
{
grades[i]=kb.nextDouble();
}
return grades;
}
public static double average(double[] grades)
{
double total = 0;
for (double i : grades)
{
total += i;
}
return total/(grades.length);
}
public static double[] deviation(double[] grades, double mean, double[] difference)
{
for (int i=0; i<grades.length; i++)
{
difference[i]=grades[i]-mean;
}
return difference;
}
public static void displayResults(String[] names, double[] grades, double[] difference, double mean)
{
System.out.println("The average score is" +mean);
System.out.println("Student Name Grade Mean Deviation");
for (int i=0; i<names.length; i++)
{
System.out.printf(names[i]);
System.out.printf("%20f", grades[i]);
System.out.printf("%20f", difference[i]);
System.out.println();
}
}
}
You never actually use the return result of the average method. You probably meant to pass that to displayResults, or assign it to mean in the main() method.
First, your average method should look more like this:
public static double average(double[] grades)
{
// Error check up front.
if (grades.length == 0) {
throw new InvalidArgumentException("length is 0");
}
// These next lines are good.
double total = 0;
for (double i : grades)
{
total += i;
}
// Then you can just divide and return.
return total / (grades.length);
}
There's no reason to pass a mean parameter to the average method. That'd be like passing a Dog to a createDog method.
But more importantly, while you call average, you don't store the result anywhere. You're just ignoring it.
If you're coming from a background with pointers, remember that Java passes primitives by value - changing mean, a double, inside the method will have no effect on the value outside the method. Instead, have
double mean = average(grades);
So the underlying reason why mean is zero is because you set it to zero, and never change it:
double mean = 0;
You are returning your mean value, but you aren't assigning the result of the method call to average to anything. What you want is to assign the result of the method to the variable:
mean = average(grades);
And in your average method, you don't need to take mean as a parameter, just declare it locally and return it.
average(grades, mean); sends copies of the variables to the average() method. The mean variable inside of average() has nothing to do with the mean variable inside of main() despite the same name. To fix the problem, you need to do something like
mean = average(grades, mean);
I also suggest that you remove the mean parameter and declare a local variable inside of average(). Then you can just do
mean = average(grades);
You have this method declared to return a value:
public static double average(double[] grades, double mean)
but in your main method, you do not use the result returned. You are then printing out the
value of the other "mean" variable which is global to that function, and is assigned a value of 0.
double mean=0;
double[] difference = new double[7];
getScores(grades);
**average(grades, mean);**
deviation(grades,mean,difference);
displayResults(names, grades, difference, mean);
I think you want :
getScores(grades);
**mean = average(grades, mean);**
deviation(grades,mean,difference);
displayResults(names, grades, difference, mean);

method in class cannot be applied to given types

I'm creating a program that generates 100 random integers between 0 and 9 and displays the count for each number. I'm using an array of ten integers, counts, to store the number of 0s, 1s, ..., 9s.)
When I compile the program I get the error:
RandomNumbers.java:9: error: method generateNumbers in class RandomNumbers cannot be applied to given types;
generateNumbers();
required: int[]
found:generateNumbers();
reason: actual and formal argument lists differ in length
I get this error for the lines of code that I call the methods generateNumbers() and displayCounts() in the main method.
public class RandomNumbers {
public static void main(String[] args) {
//declares array for random numbers
int[] numbers = new int [99];
//calls the generateNumbers method
generateNumbers();
//calls the displayCounts method
displayCounts();
}
//*****************************************************************
private static int generateNumbers(int[] numbers){
for(int i = 0; i < 100; i++){
int randomNumber;
randomNumber = (int)(Math.random() *10);
numbers[i] = randomNumber;
return randomNumber;
}
}
//*****************************************************************
private static void displayCounts(int[] numbers){
int[] frequency = new int[10];
for(int i = 0, size = numbers.length; i < size; i++ ){
System.out.println((i) + " counts = " + frequency[i]);
}
}//end of displayCounts
}//end of class
generateNumbers() expects a parameter and you aren't passing one in!
generateNumbers() also returns after it has set the first random number - seems to be some confusion about what it is trying to do.
call generateNumbers(numbers);, your generateNumbers(); expects int[] as an argument ans you were passing none, thus the error
The generateNumbers(int[] numbers) function definition has arguments (int[] numbers)that expects an array of integers. However, in the main, generateNumbers(); doesn't have any arguments.
To resolve it, simply add an array of numbers to the arguments while calling thegenerateNumbers() function in the main.
I think you want something like this. The formatting is off, but it should give the essential information you want.
import java.util.Scanner;
public class BookstoreCredit
{
public static void computeDiscount(String name, double gpa)
{
double credits;
credits = gpa * 10;
System.out.println(name + " your GPA is " +
gpa + " so your credit is $" + credits);
}
public static void main (String args[])
{
String studentName;
double gradeAverage;
Scanner inputDevice = new Scanner(System.in);
System.out.println("Enter Student name: ");
studentName = inputDevice.nextLine();
System.out.println("Enter student GPA: ");
gradeAverage = inputDevice.nextDouble();
computeDiscount(studentName, gradeAverage);
}
}
pass the array as a parameter when call the function, like
(generateNumbers(parameter),displayCounts(parameter))
If you get this error with Dagger Android dependency injection, first just try and clean and rebuild project. If that doesn't work, maybe delete the project .gradle cache. Sometimes Dagger just fails to generate the needed factory classes on changes.
public class RandomNumbers {
public static void main(String[] args) {
//declares array for random numbers
int[] numbers = new int [100];
//calls the generateNumbers method
generateNumbers(numbers); //passing the empty array
//calls the displayCounts method
displayCounts(numbers); //passing the array filled with random numbers
}
//*****************************************************************
private static void generateNumbers(int[] numbers){
for(int i = 0; i < 100; i++){
int randomNumber;
randomNumber = (int)(Math.random() *10);
numbers[i] = randomNumber;
} // here the function doesn't need to return.Since array is non primitive data type the changes done in the function automatically gets save in original array.
}
//*****************************************************************
private static void displayCounts(int[] numbers){
int count;
for(int i = 0, size = 10; i < size; i++ ){
count=0;
for(int j = 0; j < numbers.length ; j++ ){
if(i == numbers[j])
count++; //counts each occurence of digits ranging from 0 to 9
}
System.out.println((i) + " counts = " + count);
}
}//end of displayCounts
}//end of class

Categories