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();
}
}
Related
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}
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
}
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.
I have compiled with no errors, however I can complete the first loop no issues. However second go around it will prompt for Division name however the prompt for Number of employees does to. So I end up seeing Enter Division Name: Enter Number of Employees:
Not sure why this is happening, but I don't see anything out of place when looking.
If you see where I went wrong could you point to the line number or string of code.
Thanks.
import java.util.Scanner;
public class PayRoll {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name;
int employees;
double salary;
while(true) {
System.out.print("Enter Division Name: ");
name = input.nextLine();
if(name.equalsIgnoreCase("stop")) {
break;
}else {
System.out.print("Enter Number of Employees: ");
employees = input.nextInt();
while(employees <= 0) {
System.out.print("Number of Employees Must be Greater than 0, Please Re-enter: ");
employees = input.nextInt();
}
System.out.print("Enter Average Salary: ");
salary = input.nextDouble();
while(salary <= 0) {
System.out.print("Average Salary Must be Greater than 0, Please Re-enter: ");
salary = input.nextDouble();
}
Division d = new Division(name,employees,salary);
System.out.println();
System.out.println("Division " + d.getName());
System.out.println("Has " + d.getEmployees() + " Employees.");
System.out.printf("Averaging $%.2f\n",d.getSalary(),"per Employee");
System.out.printf("Making the Division total: $%.2f\n", d.getTotal());
System.out.println();
}
}
}
}
class Division {
private String name;
private int employees;
private double salary;
public Division(String name, int employees, double salary) {
this.name = name;
this.employees = employees;
this.salary = salary;
}
public double getTotal() {
return employees*salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEmployees() {
return employees;
}
public void setEmployees(int employees) {
this.employees = employees;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
while(true) {
input = new Scanner(System.in);
}
Instantiate your Scanner instance input in while loop.
just add input.nextLine(); after every input.nextInt(); OR input. nextDouble(); AS:
while(true) {
System.out.print("Enter Division Name: ");
name = input.nextLine();
if(name.equalsIgnoreCase("stop")) {
break;
}else {
System.out.print("Enter Number of Employees: ");
employees = input.nextInt();
input.nextLine(); // Add it Here
while(employees <= 0) {
System.out.print("Number of Employees Must be Greater than 0, Please Re-enter: ");
employees = input.nextInt();
input.nextLine();
}
System.out.print("Enter Average Salary: ");
salary = input.nextDouble();
input.nextLine();
while(salary <= 0) {
System.out.print("Average Salary Must be Greater than 0, Please Re-enter: ");
salary = input.nextDouble();
input.nextLine();
}
// Rest of the Code
}
To understand why you need to do this , Read Java Documentation
create a counter variable out of the while loop. let's say counter == 0, increment it at the end of the loop so you won't create a problem in the initial loop using my solution.
int counter = 0;
While(){
System.out.print("Enter Division Name: ");
if(counter != 0){
input.nextLine();
}
name = input.nextLine();
counter++;
}
I'm stuck. This is what I have written so far, but I don't know how to set up for a method call to prompt for the total. I need the individual totals for all items in the array to be added to get a total cost and it needs to be displayed at the end of the program. Please, any advice is helpful. I have to be to work soon and need to turn it in before I go. Thanks
MAIN FILE
package inventory2;
import java.util.Scanner;
public class RunApp
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
Items theItem = new Items();
int number;
String Name = "";
System.out.print("How many items are to be put into inventory count?: ");
number = input.nextInt();
input.nextLine();
Items[]inv = new Items[number];
for(int count = 0; count < inv.length; ++count)
{
System.out.print("\nWhat is item " +(count +1) + "'s name?: ");
Name = input.nextLine();
theItem.setName(Name);
System.out.print("Enter " + Name + "'s product number: ");
double pNumber = input.nextDouble();
theItem.setpNumber(pNumber);
System.out.print("How many " + Name + "s are there in inventory?: ");
double Units = input.nextDouble();
theItem.setUnits(Units);
System.out.print(Name + "'s cost: ");
double Price = input.nextDouble();
theItem.setPrice (Price);
inv[count] = new Items(Name, Price, Units, pNumber);
input.nextLine();
System.out.print("\n Product Name: " + theItem.getName());
System.out.print("\n Product Number: " + theItem.getpNumber());
System.out.print("\n Amount of Units in Stock: " + theItem.getUnits());
System.out.print("\n Price per Unit: " + theItem.getPrice() + "\n\n");
System.out.printf("\n Total cost for %s in stock: $%.2f", theItem.getName(), theItem.calculateTotalPrice());
System.out.printf("Total Cost for all items entered: $%.2f", theItem.calculateTotalPrice()); //i need to prompt for output to show total price for all items in array
}
}
}
2ND CLASS
package inventory2;
public class Items
{
private String Name;
private double pNumber, Units, Price;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
//constructor
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public double calculateAllItemsTotalPrice() //i need method to calculate total cost for all items in array
{
return (TotalPrice );
}
}
In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like
float total;
total += theItem.getUnits() * theItem.getPrice();
total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.
The total of 7 numbers in an array can be created as:
import java.util.*;
class Sum
{
public static void main(String arg[])
{
int a[]=new int[7];
int total=0;
Scanner n=new Scanner(System.in);
System.out.println("Enter the no. for total");
for(int i=0;i<=6;i++)
{
a[i]=n.nextInt();
total=total+a[i];
}
System.out.println("The total is :"+total);
}
}