I have to create a code that takes user input for grades based on a students name that the user has inputted.
The input is to stop when a number less than 0 is inputted and the output should be the student name, the total of all the scores, and the average score.
For some reason I cannot get the average or the total to print, and my counter in my student class is showing an error "remove this token '++'"
Here is my main class, and my student class :
/**
* COSC 210-001 Assignment 2
* Prog2.java
*
* description
*
* @author Tristan Shumaker
*/
import java.util.Scanner;
public class main {
public static void main( String[] args) {
double[] addQuiz = new double[99];
int counter = 0;
//Creates new scanner for input
Scanner in = new Scanner( System.in);
//Prompts the user for the student name
System.out.print("Enter Student Name: ");
String name = in.nextLine();
// requests first score and primes loop
System.out.print("Enter Student Score: ");
int scoreInput = in.nextInt();
while( scoreInput >= 0 ) {
System.out.print("Enter Student Score: ");
scoreInput = in.nextInt();
counter++;
}
System.out.println( );
System.out.println("Student name: " + name);
System.out.printf( "\nAverage: %1.2f", total(addQuiz, counter) );
System.out.printf( "\nAverage: %1.2f", average(addQuiz, counter) );
}
}
and my student class:
public class Student {
private String name;
private int total;
private int counter;
public Student() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void addQuiz( int scoreInput) {
total += scoreInput;
int counter++;
}
public static double average( double[] addQuiz, int counter ) {
double sum = 0;
for( int t = 0; t < counter; t++) {
sum += addQuiz[t];
}
return (double) sum / counter;
}
}
Any help you guys are able to give would be greatly appreciated
change int counter++;
in the addQuiz()
method to just counter++;
, as otherwise you're trying to declare a variable with identifier counter++
which is not a valid identifier. Also since you've declared average()
to be a static method on the Student
class you'll need to call it like so:
Student.average(addQuiz, counter);
I'm not seeing a definition for total()
in your code so I don't know if the same would apply to that.
EDIT
To answer why average()
is returning zero, it looks like you never set any values in the addQuiz
double array that you're passing in, so it will contain all zeros, and as a result sum
will be 0. I think what you want to do is to change your while loop in the main method to put the scoreInput
value in the array at the counter
index like so:
while( scoreInput >= 0 ) {
System.out.print("Enter Student Score: ");
scoreInput = in.nextInt();
addQuiz[counter] = scoreInput;
counter++;
}