How to fix my counter and average calculator - java

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, thanks in advanced.

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++;
}

In your main class you are not using your Student class at all.
Consider doing
Student student = new Student (name);
and then using the methods such as
student.addQuiz (scoreInput);
and later
student.getTotal ();
etc.
You also do not need to store the variable counter in the Student Object at all as it is being passed as a parameter.

Related

how to prompt user to input array values and create a data type in java

I am working on a java code where it should prompt the user to input the grades of N amount of students and it should output the highest grade, My code is working well but I want to give the user ability to enter the content of the array and I want to create a data type called Student for example for the array.
public class Test3 {
static double grades[] = {85, 99.9, 78, 90, 98};
static double largest() {
int i;
double max = grades[0];
for (i = 1; i < grades.length; i++)
if (grades[i] > max)
max = grades[i];
return max;
}
public static void main(String[] args)
{
System.out.println("Highest grade is : " + largest());
}
}
Any help would be really appreciated.
First, you should create the Student class:
public class Student {
private double grade;
// empty constructor
public Student() {}
// all args constructor
public Student(double grade) {
this.grade = grade;
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
this.grade = grade;
}
#Override
public String toString() {
return "Student{" +
"grade=" + grade +
'}';
}
}
To avoid repetitive code, you can use the Lombok library. It creates for you the constructors, getters, setters, toString(), and much more.
After, you can create a method to input students grades.
public static Student[] inputStudens() {
Scanner sc = new Scanner(System.in);
System.out.println("How many students?");
int N = sc.nextInt();
Student[] students = new Student[N];
for (int i=0; i<N; i++) {
System.out.println("What's the grade for student " + i + ":");
double grade = sc.nextDouble();
Student student = new Student(grade);
students[i] = student;
}
return students;
}
And... using your already made max finder, but returning the Student instead.
public static Student maxGrade(Student[] students) {
int max = 0;
for (int i = 1; i < students.length; i++) {
if (students[i].getGrade() > students[max].getGrade()) {
max = i;
}
}
return students[max];
}
Now we just need to call these methods in main().
public static void main(String[] args) {
Student[] students = inputStudens();
Student student = maxGrade(students);
System.out.println("Student with highest grade is: " + student);
}
You can create an object and use that object to invoke the array to store value. For example:
test3obj= new Test3(); // creating an object.
Use test3obj to invoke the array to store values like:
test3obj.grades[i]=(object of scanner class).nextDouble();
Object of scanner class:
Scanner obj=new Scanner(System.in);

How can I use the class I created in my main in java?

I'm working on Java code that takes an array of type Student and the number of students and it should return the average of students CGPA and I should use a class called Student which I have already done but I want to include it in my main.
Main code that calculates average of CGPA:
import java.util.*;
public class Test4{
public static void main(String [] args){
Scanner adnan = new Scanner(System.in);
System.out.println("Enter number of students : ");
int length = adnan.nextInt();
double [] input = new double[length];
System.out.println("Enter Cgpa of students : ");
for( int i = 0; i < length; i++){
input[i] = adnan.nextDouble();
}
double averageCgpa = averageCgpa(input);
System.out.println("Average of students Cgpa : " + averageCgpa);
adnan.close();
}
public static double averageCgpa(double [] input){
double sum = 0f;
for ( double number : input){
sum = sum + number;
}
return sum / input.length;
}
}
My Student class :
public class Student {
private double grade;
public Student() {}
public Student(double grade) {
this.grade = grade;
}
public double getGrade() {
return grade;
}
public void setGrade(double grade) {
this.grade = grade;
}
public String toString() {
return "Student{" +
"grade=" + grade +
'}';
}
}
I need to implement the class to work with the main but I need to keep them each in a different file.
Make sure they are in the same package, and then you can use the Student class directly in the Main class.
Instantiate from the Student class to use it in the Main class
package ThePackageYourClassesAreIn;
public class Test4{
public static void main(String [] args){
double grade = 100.0; // some grade
Student student = new Student(grade); // instantiate from Student
// Do stuff with student object
}
public static double averageCgpa(double [] input){
// Do stuff
}
}
If the Class files were from different packages, mention that package, too.
import OtherPackage.Student;
Here is how you can incorporate the Student class into your code. Just use a List of Student. Add a Student each time you input a grade and when you want to calculate the average just iterate the list of Students and call getGrade instead of using your double primitive types.
Test4.java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test4 {
public static void main(String[] args) {
try(Scanner adnan = new Scanner(System.in)) {
System.out.print("Enter number of students: ");
int length = adnan.nextInt();
List<Student> input = new ArrayList<>(length);
System.out.println("Enter Cgpa of students: ");
for (int i = 0; i < length; i++) {
System.out.print("Student " + (i + 1) + ": ");
input.add(new Student(adnan.nextDouble()));
}
double averageCgpa = averageCgpa(input);
System.out.println("Average of students Cgpa: " + averageCgpa);
}
}
public static double averageCgpa(List<Student> input) {
double total = 0f;
for (Student s: input) {
total += s.getGrade();
}
return total / input.size();
}
}
Student.java
public class Student {
private final double grade;
public Student(double grade) {
this.grade = grade;
}
public double getGrade() {
return grade;
}
public String toString() {
return "Student{" + "grade=" + grade + '}';
}
}
This has no package statements as it is for demo purposes only. As long are both classes are in the same package (in this case the default package) then you won't need an import.

Java Program to

At the moment my professor wants to do a program like below, I'm having difficulty achieving that, I'm seeking help to help me push through. Here is the instructions and what I have so far. Cristisim and advice accepted!
1) The highest score and the student name
2) The lowest score and the student name
3) Average score of the class
4) Display the student names and their scores in decreasing order of their scores with marks: if their score is above average,
mark with a ‘+’ sign; if their score equals to average, mark with a ‘=’; otherwise, mark with a’-‘.
Example Image of what I have to do:
https://i.gyazo.com/403819a89bae613452dd8278b0612d81.png
My problems are, I don't know how to sort the arrays to get the highest score and print it out with the corresponding name that goes with it.
I also don't know how to put the numbers like 1. Name, 2. Name because it starts with 0 first.
My work:
public static void main(String[] args) {
System.out.println("********** Students and Scores ************");
Scanner input = new Scanner(System.in);
System.out.print("How many students in your class?: ");
int numStudents = input.nextInt();
double[] scores = new double[numStudents];
String[] students = new String[numStudents];
for (int i = 0; i < numStudents; i++) {
System.out.print(i + ". Name: ");
students[i] = input.next();
System.out.print("Score: ");
scores[i] = input.nextDouble();
}
double sum = 0;
for(int i=0; i < scores.length ; i++)
sum = sum + scores[i];
double average = sum / scores.length;
System.out.println("*************** Results *****************");
System.out.println("Average: " + average);
System.out.println("******* End of Students and Scores *********");
}
Well you have not taken the good approach for this kind of given problem...
In Java there are classes, so you can use them and define your Student class like following:
public class Student {
//variables
private String name;
private double score;
//constructor
public Student(String name, double score) {
this.name = name;
this.score = score;
}
//getters and setters
public String getName() {
return this.name;
}
public double getScore() {
return this.score;
}
public void setName(String name) {
this.name = name;
}
public void setScore(double score) {
this.score = score;
}
}
You can create classes to handle your operations and to work with student class
or you can do something like this:
public static void main(String[] args) {
List<Students> students = new ArrayList<Students>();
students.add("Jhon", 10);
students.add("Mary", 5.5);
students.add("Ana", 3);
Iterator i = students.iterator();
//iterate through your students list like tihs;
while(i.hasNext()) {
System.out.println("Student = "+ i.next());
}
// do what ever you want with the list
// make your calculations and stuff, what your problem required
}

Issue with trying to fix my printf statement

I need to fix my addQuiz() in my student class. Then, with that class, I pull all the info into my main of prog2. I have everything working except two things. I need to get the formula fixed for my addQuiz() so it totals the amount of points entered, and fix the while statement in my main so that I can enter a word to tell the program that I am done entering my quizzes.
Here is my main file.
import java.util.Scanner;
public class Prog2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Student student = new Student();
//creates array for quizzes
double[] grades = new double[99];
//counter for total number of quizzes
int num = 0;
//requests user to enter students name
System.out.print("Enter name of student: ");
String name = in .nextLine();
//requests user to enter students quizzes
System.out.print("Enter students quiz grades: ");
int quiz = in .nextInt();
while (quiz >= 1) {
System.out.print("Enter students quiz grades: ");
quiz = in .nextInt();
grades[num] = quiz;
num++;
}
//prints the name, total, and average of students grades
System.out.println();
System.out.println(name);
System.out.printf("\nTotal: ", student.addQuiz(grades, num));
System.out.printf("\nAverage: %1.2f", student.Average(grades, num));
}
}
here is my student file:
public class Student {
private String name;
private int total;
private int quiz;
static int num;
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 int getQuiz() {
return quiz;
}
public void setQuiz(int quiz) {
this.quiz = quiz;
}
public static double addQuiz( double[] grades, int num){
int totalQuiz = 0;
for( int x = 0; x < num; x++){
totalQuiz += grades[x];
}
return totalQuiz;
}
public static double Average( double[] grades, int num){
double sum = 0;
for( int x = 0; x < num; x++){
sum += grades [x];
}
return (double) sum / num;
}
}
Any help would be much appreciated!
Your requirement is not clear but as I guess it should be something like this.
Prog2 class:
public static void main(String[] args) {
// requests user to enter students name
System.out.print("Enter name of student: ");
Scanner in = new Scanner(System.in);
String name = in.nextLine();
Student student = new Student(name);
System.out.print("Enter number of quiz: ");
int count = in.nextInt();
for (int i = 0; i < count; i++) {
// requests user to enter students quizzes
System.out.print("Enter students quiz grades: ");
int quiz = in.nextInt();
student.addGrade(quiz);
}
// prints the name, total, and average of students grades
System.out.println(name);
System.out.println("Total: " + student.getTotal());
System.out.println("Average: " + student.getAverage());
}
Student class:
private String name;
private List<Double> grades = new ArrayList<Double>();
public Student(String name) {
super();
this.name= name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addGrade(double grade) {
this.grades.add(grade);
}
public double getTotal() {
double total = 0;
for (double grade : grades) {
total += grade;
}
return total;
}
public double getAverage() {
return (double) getTotal() / grades.size();
}
Accept the answer if it helps.
Well for the stop condition you could try something like this
String stopFrase="stop";
String userInput="";
int quiz;
//Other code
for(;;) //This basically means loop until I stop you
{
System.out.print("Enter students quiz grades type 'stop' to finish:");
userInput=in.nextLine();
if(userInput.equals(stopFrace))
{
break;//Stop the loop
}
quiz= Integer.parseInt(userInput);
//The rest of your code
}
Your addQuiz() method seems fine, if you are not getting the desired result please check your parameters, specifically make sure that number matches the number of quiz entered.

Inheritance & Polymorphism Assignment

I need to write an application to display the name and ID number of each student and to calculate whether they have passed or failed. I need to have 4 different classes student, studenttest, undergraduate, postgraduate.
So far this is what I have:
Student
class Student {
//private data members
private long idNumber = 0;
private String name = "Not Given";
private int markForMaths = 0;
private int markForEnglish = 0;
private int markForEconomics = 0;
private int markForPhilosophy = 0;
private int markForIT = 0;
//Default constructor
public Student() {
name = "Not Given";
idNumber = 0;
markForMaths = 0;
markForEnglish = 0;
markForEconomics = 0;
markForPhilosophy = 0;
markForIT = 0;
}
//Constructs a new Student with passed name and age parameters.
public Student(String studentName, long studentIdNumber) {
name = studentName;
idNumber = studentIdNumber;
}
//Returns the name of student.
public String getName( ) {
return name;
}
//Returns the idNumber of student.
public long getIdNumber( ) {
return idNumber;
}
//entermarks()
//enter all subject marks given as args
public void enterMarks(int maths, int english, int economics, int philosophy, int informationTechnology)
{
markForMaths = maths;
markForEnglish = english;
markForEconomics = economics;
markForPhilosophy = philosophy;
markForIT = informationTechnology;
}
//getMathsMark()
//return mark for maths
public int getMathsMark()
{
return markForMaths;
}
//getEnglishMark()
//return mark for English
public int getEnglishMark()
{
return markForEnglish;
}
//getEconomicsMark()
//return mark for Economics
public int getEconomicsMark()
{
return markForEconomics;
}
//getPhilosophyMark()
//return mark for Philosophy
public int getPhilosophyMark()
{
return markForPhilosophy;
}
//getITMark()
//return mark for IT
public int getITMark()
{
return markForIT;
}
//calculateAverageMark()
//return the average of the three marks
public double calculateAverageMark()
{
return ((markForMaths + markForEnglish +
markForEconomics + markForPhilosophy + markForIT) / 3.0);
}
//Sets the name of student.
public void setName(String studentName ) {
name = studentName;
}
//Sets the idNumber of student.
public void setIdNumber(long studentIdNumber ) {
idNumber = studentIdNumber;
}
}//end class
Undergraduate
public class Undergarduate extends Student{
}
Postgraduate
public class Postgraduate extends Student{
}
StudentTest
import java.util.Scanner;
public class StudentTest {
static int array;
//create method createArray
public static Student[] createArray() {
Scanner int_input = new Scanner(System.in);
//user enters size of array
System.out.print("Enter Size of Array: ");
array = int_input.nextInt();
Student[] array = new Student[0];
//read user input as arraySize
return new Student[5];
}//end method
//create method populateArray
public static void populateArray(Student[] array) {
Scanner string_input = new Scanner(System.in);
Scanner long_input = new Scanner(System.in);
Scanner int_input = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
Student student = new Student(); // new student
//set name
System.out.println("Enter Student Name: ");
student.setName(string_input.nextLine());
//set ID number
System.out.println("Enter Student ID Number: ");
student.setIdNumber(long_input.nextLong());
//set Marks
System.out.println("Enter Marks");
student.enterMarks(int_input.nextInt());
//put new student into array passed to the method
array[i] = student;
}//end for loop
}//end method
//create method display Array
public static void displayArray(Student[] array){
System.out.println("Array Contents");
for (Student s : array) {
System.out.println(String.format("%s %d", s.getName(),
s.getIdNumber(), s.getEnglishMark(), s.getMathsMark(),
s.getEconomicsMark(), s.getPhilosophyMark(), s.getITMark(),
s.calculateAverageMark()));
}//end for loop
}//end method
public static void main(String [] args) {
// create array of size specified by user
Student[] students = createArray();
//populate this array with data from user
populateArray(students);
//display array contents
displayArray(students);
}//end main method
}//end class
I keep getting an error in the studenttest on the line
student.enterMarks(int_input.nextInt());
the error reads:
The method enterMarks(int, int, int, int, int, int) in the type Student is not applicable for the arguments (int)
As your class Student expects marks for each subject (english, maths, etc..), change your StudentTest class so that it passes each and every subject as input to enterMarks method.
Change your method call from:
student.enterMarks(int_input.nextInt());
TO
student.enterMarks(int_input.nextInt(), int_input.nextInt(), int_input.nextInt(), int_input.nextInt(), int_input.nextInt(), int_input.nextInt());//to make it more readable and usable, first take input from keyboard by asking user to enter the number, assign to individual marks variable and then pass it to the method.
You are trying to invoke method enterMarks(int) but there is only enterMarks(int, int, int, int, int, int) method defined in Student class.

Categories