Issue with trying to fix my printf statement - java

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.

Related

How do I calculate the average of an array of objects where the objects contain string and integer variables?

This is the code I have currently.
Below is my object "Student"
`public class Student {
private String name;
private int score;
public Student() {
}
public Student(String name, int score){
this.name = name;
this.score = score;
}
public void setName(String name) {
this.name = name;
}
public void setScore(int score) {
this.score = score;
}
public void readInput() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the student's name: ");
this.name = keyboard.next();
System.out.println("Please enter the student's score: ");
this.score = keyboard.nextInt();
}
public void writeOutput() {
System.out.println("The student's name and score: " + name + ", " + score + "%");
}
public String getName(String name) {
return this.name;
}
public int getScore(int score) {
return score;
}
}`
Then in another class "TestReporter" I am attempting to compute the averageof the array of ourClass[] .
I am also to find the highest score within the ourClass array but don't know how to seperate scores from students , I probably overcomplicated the question but any help would be appreciated.
`import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
public class TestReporter {
private int highestScore;
private double averageScore;
private Student[] ourClass;
private int numOfStudents;
public TestReporter(){
}
public void getData() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students");
numOfStudents = keyboard.nextInt();
ourClass = new Student[numOfStudents];
for (int i = 0; i < numOfStudents ; i++) {
ourClass[i] = new Student();
ourClass[i].readInput();
}
}
public void computeStats() {
double total = 0;
for (int i = 0; i < numOfStudents; i++) {
total = total + ourClass[i];
}
averageScore = total / ourClass.length;
}
public void displayResults() {
for (Student Student: ourClass) {
Student.writeOutput();
}
}
}`
To get Highest Score declare variable in compute StateStats
public void computeStats() {
double total = 0;
int highestScore = 0;
for (int i = 0; i < numOfStudents; i++) {
int score = ourClass[i].getScore();
total = total;
if(score > highestScore)
highestScore = score;
}
averageScore = total / ourClass.length;
System.output.println("Average Score = "+averageScore;
System.output.println("Highest Score = " highestScore;
}
then add following to displayResults()
computeStats();
Also:
change Setters as mentioned by {QBrute}

Array won't output total of numbers

I am trying to allow the user to submit their test scores then get the total scores and the average score. I have a separate class called student to help simplify some tasks.
This is the Student Class:
public class Student {
private String name;
private int numOfQuizzes;
private double totalScore;
public Student(String name){
this.name = name;
}
public String getName() {
return name;
}public void addQuiz(int score){
numOfQuizzes++;
totalScore += score;
}public double getTotalScore() {
return totalScore;
}
public double getAverageScore(){
return totalScore/(double)numOfQuizzes;
}
}
Then this is my main class so far.
ArrayList<String> scores = new ArrayList<String>();
Scanner nameInput = new Scanner(System.in);
System.out.print("What is your name? ");
String name = nameInput.next();
Scanner scoreInput = new Scanner(System.in);
while (true) {
System.out.print("Please enter your scores (q to quit): ");
String q = scoreInput.nextLine();
scores.add(q);
if (q.equals("q")) {
scores.remove("q");
Student student = new Student(name);
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
break;
}
}
}
}
This is the current output.
What is your name? tom
Please enter your scores (q to quit): 13
Please enter your scores (q to quit): 12
Please enter your scores (q to quit): 5
Please enter your scores (q to quit): q
Students Name: tom
Total Quiz Scores: 0.0
Average Quiz Score: NaN
When you read in your values, you need to check whether it's a string or an int, you only want to add integers. You might do something like:
try{
do{
String q = scoreInput.nextLine();
if(q.equals("q"){
//Do something, like break
break;
}
int numVal = Integer.valueOf(q);
scores.addQuiz(numVal);
} catch (Exception e){
//Handle error of converting string to int
}
}while(true);
//Once you have all the scores, be sure to call your averageScore method
averageScore();
Once you have the scores, your average score method should be something like:
public double averageScore(){
if(scores != null){
for(int score : scores){
totalScore += score;
}
return totalScore/scores.size();
}
Your Student class might look like this:
public class Student {
private String name;
private int numOfQuizzes;
private double totalScore;
private ArrayList<Integer> scores;
public Student(String name){
this.name = name;
scores = new ArrayList<Integer>();
}
public String getName() {
return name;
}public void addQuiz(int score){
scores.add(score);
}
public double getTotalScore() {
for(int score : scores){
totalScore += score;
}
return totalScore;
}
public double averageScore(){
if(scores != null){
for(int score : scores){
totalScore += score;
}
return totalScore/scores.size();
}
}

Sorting student test scores in an array

I am given an integer, N, which is the number of test scores that will be inputted. For each line, N, there will be a student name followed their test score. I need to compute the sum of their test scores & print the the second-smallest student's name.
So, what I would do is create an array of classes for the students. The class would have two instance variables for the name and score. Then when all the input is done, all you need to do is get them. Here is the code that I came up with for that exact thing.
import java.util.*;
public class testScores {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Student[] students = new Student[n];
for(int i = 0; i < n; i++){
students[i] = new Student();
System.out.print("Enter the student's name");
students[i].setName(scan.next());
scan.nextLine();
System.out.print("Enter the student's score");
students[i].setScore(scan.nextInt());
scan.nextLine();
}
int total = 0;
int smallest_name = 0;
for(int i = 0; i < n; i++){
total+=students[i].getScore();
if(students[i].getName().length() < students[smallest_name].getName().length())
smallest_name = i;
}
int second_smallest = 0;
for(int i = 0; i < n; i++){
if(students[i].getName().length() > students[smallest_name].getName().length() && students[i].getName().length() < students[second_smallest].getName().length())
second_smallest = i;
}
System.out.println("The sum of the scores is: " + total);
System.out.println("The second smallest name is: " + students[second_smallest].getName());
}
}
class Student{
private String name;
private int score;
public Student(){}
public void setScore(int n){
score = n;
}
public void setName(String n){
name = n;
}
public int getScore(){
return score;
}
public String getName(){
return name;
}
}

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
}

How to fix my counter and average calculator

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.

Categories