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);
Related
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
I keep receiving an error in the below codetelling me that the type must be an array but its returning a double for "total[agentnumber]" in the print statement. Can anyone explain this and how I might solve it in this context?
My goal: Write code where I input the number of periods, interest rates, and number of agents (where each agent's is assigned a principal equal to its agent number i.e. agent 1 receive 100, agent 2 receives 200, etc.) and print the balances of each agent. I want to do this in a loop rather than use the compound interest formula because I am trying to learn how to use Java.
Other issue: This is a bit crazily set up because I do not know how to return the results of the for loops. Where should I place "return" and what should I be returning, supposing that I am interested in ultimately printing the equivalent of agent[agentnumber].money for each of the agents.
public class Person{
public double money; // initialize
Person(double cash){
money = cash;
}
}
public class Bank {
public static double bank(double rate, double periods, int agents){
Person[] agent = new Person[agents];
double total;
for( int agentnumber = 0; agentnumber < agents; agentnumber++) {
agent[agentnumber] = new Person((agentnumber+1)*100); // assign starting incomes and instantiate players
for(int months = 0; months < periods; months++){
agent[agentnumber].money = agent[agentnumber].money*(1.0 + rate);
total = agent[agentnumber].money;
System.out.println("The total balance of player " + agentnumber + " is " + total[agentnumber]);
}
}
}
public static void main(String[] args) {
bank(0.05,120,3);
}
}
total is a double, so just print totalout instead of total[agentnumber]
I keep receiving an error in the below code telling me that the type must be an array but its returning a double for "total[agentnumber]" in the print statement. Can anyone explain this and how I might solve it in this context?
You get this error message because total is a double, not an array. In order to use [] the type must be an array. The solution is to print total instead of total[agentnumber].
Where should I place "return" and what should I be returning, supposing that I am interested in ultimately printing the equivalent of agent[agentnumber].money for each of the agents.
As your program is written right now, you'll get an error because you have declared that bank() will return a double, but you have no return statement in bank(). It's unclear why you'd want to return anything from bank(). You probably want to change
public static double bank(double rate, double periods, int agents)
to
public static void bank(double rate, double periods, int agents)
and then you don't need to return anything.
What and where should I be returning?
You seem to just want to print out the values of an array, so nothing needs returned. In that case, you could make the method have a void return type. It also isn't really clear why you needed the array because the local agents variable isn't needed by the main method, so if you did want the array, you should return Person[] instead of double...
You could also clean up the code like so.
public class Bank {
public static Person[] bank(double rate, double periods, int agents){
Person[] agent = new Person[agents];
for( int agentnumber = 0; agentnumber < agents; agentnumber++) {
Person p = new Person((agentnumber+1)*100); // assign starting incomes and instantiate players
for(int months = 0; months < periods; months++){
p.money = p.money*(1.0 + rate);
System.out.printf("The total balance of player %d at month %d is %.2f\n", agentnumber, months, p.money);
}
agent[agentnumber] = p;
}
return agent;
}
public static void main(String[] args) {
Person[] agents = bank(0.05,120,3);
}
}
I've had a go at rewriting your code above and ensured it compiles. There are a few best practice things I would change if this wasn't just a demonstration which I've added in comments
public class Bank {
public static void main(String[] args) {
Bank bank = new Bank(0.05,120,3);
}
// For readability and simplification I would make this public and
// move it into it's own file called Person.java
private class Person {
public double money;
Person(double cash){
money = cash;
}
}
public Bank(double rate, double periods, int numberOfAgents) {
Person[] agent = new Person[numberOfAgents];
// Typical java convention is to use camel case so
// agentnumber would become agentNumber
for( int agentnumber = 0; agentnumber < numberOfAgents; agentnumber++) {
agent[agentnumber] = new Person((agentnumber+1)*100);
for(int months = 0; months < periods; months++){
agent[agentnumber].money = agent[agentnumber].money*(1.0 + rate);
}
System.out.println("The total balance of player " + agentnumber + " is " + agent [agentnumber].money);
}
}
}
So I have to make a program in class and i'm having some trouble.
I have to call the examAverage method, which has parameters and i'm not sure how to. Also, in the user prompts method, I have to make a loop in main that call user prompts method and ask the user to input their exam score 3 times to get the average. I hope I explained it well. Im not very good at programming.
package project5;
import java.util.*;
public class Project5 {
static final int NUM_EXAMS = 3;
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
//declare variable
double Average;
double examScore1 = 0;
double examScore2 = 0;
double examScore3 = 0;
double Average = examAverage(examScore1, examScore2, examScore3) / NUM_EXAMS;
printWelcome();
userPrompts();
display();
}
static void printWelcome() {
System.out.println("Welcome to the Exam Average Calculator");
}
public static void userPrompts() {
System.out.println("Please enter your 1st exam score.");
double examScore1;
examScore1 = console.nextDouble();
System.out.println("Please enter your 2nd exam score.");
double examScore2;
examScore2 = console.nextDouble();
System.out.println("Please enter your 3rd exam score.");
double examScore3;
examScore3 = console.nextDouble();
}
public static void display() {
double examAverage = 0;
}
public static double examAverage(double examScore1, double examScore2, double examScore3, double sum, double NUM_EXAMS) {
double Average;
sum = examScore1 + examScore2 + examScore3;
Average = (double) sum / NUM_EXAMS;
return Average;
}
public static void displayAverage(double Average) {
Object[] examAverage = null;
System.out.println("Your exam average is %.2f%", examAverage);
}
public static double examAverage(double examScore1, double examScore2, double examScore3) {
double Average;
{
return double Average
I don't want to do your homework for you but you call a method with paramaters severals times in your code. For example inside your main:
examAverage(examScore1, examScore2, examScore3)
you call the examAverage method passing in 3 variables. Your three variables are all set to 0, so that makes no sense. you probably should call your userPrompts before you call your examAverageMethod to initialize your examscores.
your program looks like it's almost done, think about the order of how you want to do it. good luck
So your exam average function is all messed up, what you want is it to take number of exams and the individual values and return the average.
So you make the function like this because you don't need to have sum as a parameter.
public static double examAverage(double examScore1, double examScore2, double examScore3, double NUM_EXAMS) {
double Average;
double sum = examScore1 + examScore2 + examScore3;
Average = sum / NUM_EXAMS;
return Average;
}
So when you call this function, you need to give it 4 values
so call it like this
double Average = examAverage(examScore1, examScore2, examScore3, 3);
That should solve your issue with the function. Let me know if I didn't explain it clearly enough or if you want me to elaborate.
You also have an issue on what order you call your code.
First, you want to welcome the user, then you want to ask them for their values, then you want to use those values to calculate the average and then you want to print that average so do this instead.
//declare variable
double Average;
double examScore1 = 0;
double examScore2 = 0;
double examScore3 = 0;
//Welcomes user, then prompts for exam values, calculates average using those values, and finally displays the average
printWelcome();
userPrompts();
double Average = examAverage(examScore1, examScore2, examScore3, 3);
System.out.println("your average is" + Average)
Also, delete your Display() and DisplayAverage() functions, they are useless.
On way would be to call your variables static by defining at class level like:
private static double examScore1 = 0;
private static double examScore2 = 0;
private static double examScore3 = 0;
Other best way would be to wrap all these variables in a class (or better create a list/array) and pass that call in userPrompts method and populate it and then using same object you calculate average.
Regarding looping, here's how you could do it:
create a counter and initialize it with 0.
while count <= 3
do
ask input from user
calculate average
display the average
done
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.
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