Enter name and grades from user input to get average grade - java

I am working on a code where you have a students name and his grades and it prints his name total scores and his average scores. I want to make it more functional in allowing the user to input there name and scores and get all that info back. I may try to further this into a class average where it allows to input multiple individual names, scores, and average, print each one separately then showing the class average. This is a second thought though, as I need to have user input of grades and names first.
This is what I have so far.
I have a separate class to make some things simpler.
public class Student {
private String name;
private int numOfQuizzes;
private int totalScore;
public Student(String name){
this.name = name;
}
public String getName() {
return name;
}
public int getTotalScore() {
return totalScore;
}
public void addQuiz(int score) {
totalScore = totalScore + score;
numOfQuizzes++;
}
public double getAverageScore(){
return totalScore/(double)numOfQuizzes;
}
}
Then i have the main method:
public static void main(String[] args) {
Scanner nameInput = new Scanner(System.in);
System.out.print("What is your name? ");
String name = nameInput.next();
Student student = new Student(name);
student.addQuiz(96);
student.addQuiz(94);
student.addQuiz(93);
student.addQuiz(92);
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
}
This is what it prints out currently:
What is your name? Tom
Students Name: Tom
Total Quiz Scores: 375
Average Quiz Score: 93.75
UPDATE:
This is what i have done so far. i added a loop and trying to use my student class but it doesn't seem to work with the array.
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;
}
}
}
}

Since you are only learning the language just yet, I'll give you a few suggestions to send you on your way. You might want to use a while-loop to consistently ask the user for a new grade until they've given you an empty line or something. You can reuse your scanner to read the new grades and they can be converted to integers using Integer.parseInt. Hopefully this'll allow you to write your code further, it's already looking great :).
EDIT
There are several points which can be improved upon in your edited code. The following shows some of them (using import java.io.Console;):
Scanner inp = new Scanner(System.in);
// Request the name
System.out.print("What is your name? ");
String name = inp.nextLine();
// Create the student object
Student student = new Student(name);
// Ask for the grades
System.out.print("Please enter your scores (q to quit): ");
String grade = inp.nextLine();
while (!grade.equals("q")) {
// Convert the grade to an integer and pass it
student.addQuiz(Integer.parseInt(grade));
// Request a new grade
grade = inp.nextLine();
}
// Report the results
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());

Related

How to compare attributes from multiple class instances?

Alright, so here's the pickle. I'm taking this course that teaches logic programming in Java. I only know a bit of JavaScript so Java is pretty much alien tech for me.
I'm doing this assignment where I need to create a conference manager app (which is console-based only). Each conference holds lectures (as many as you want). Each conference has attributes such as the conference manager's name, his telephone number, his hourly rate etc; and it's the same for the lectures. I wanted to be able to input these data with Scanner method. So this is what I did so far:
Started creating two classes:
1) a conference creator
import java.util.*;
public class Conference {
String nameConference;
String nameManagerConference;
String telManagerConference;
String dateStartConference;
String dateEndConference;
float hourlyRateManager;
float hoursAmountConference;
public void setConferenceData() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Conference name: ");
this.nameConference = keyboard.nextLine();
System.out.print("Conference manager name: ");
this.nameManagerConference = keyboard.nextLine();
System.out.print("Conference manager telephone number: ");
this.telManagerConference = keyboard.nextLine();
System.out.print("Conference start date: ");
this.dateStartConference = keyboard.nextLine();
System.out.print("Conference end date: ");
this.dateEndConference = keyboard.nextLine();
System.out.print("Manager hourly rate: ");
this.hourlyRateManager = keyboard.nextFloat();
System.out.print("Conference amount of hours: ");
this.hoursAmountConference = keyboard.nextFloat();
System.out.println(this.nameManagerConference + ", manager of the conference " + "\"" + this.nameConference +"\"" + ", cost R$ " + (this.hoursAmountConference * this.hourlyRateManager));
}
}
2) a lecture creator
import java.util.*;
public class Lectures {
float totalCost = 0;
String lecturesList = "Lectures list: ";
ArrayList<Float> arrLecturesCostTotal = new ArrayList<>();
ArrayList<String> listLectures = new ArrayList<>();
public void getLecturesTotalCost() {
for (int i = 0; i < arrLecturesCostTotal.size(); i++) {
totalCost += arrLecturesCostTotal.get(i);
}
System.out.println("The total lectures cost is $ " + totalCost);
}
public void getLecturesList() {
for (int i = 0; i < listLectures.size(); i++) {
lecturesList += "\n" + "- " + listLectures.get(i);
}
System.out.println(lecturesList);
}
public class Lecture{
String lectureTitle;
String lectureStartHour;
String lecturerName;
String lecturerTelephone;
String lectureDescription;
float lecturerHourlyRate;
float lectureHoursAmount;
float lectureCost = 0;
public void setDataLecture() {
Scanner keyboard = new Scanner(System.in);
System.out.print("Lecture title: ");
this.lectureTitle = keyboard.nextLine();
System.out.print("Lecture start time: ");
this.lectureStartHour = keyboard.nextLine();
System.out.print("Lecturer name: ");
this.lecturerName = keyboard.nextLine();
System.out.print("Lecturer telephone number: ");
this.lecturerTelephone = keyboard.nextLine();
System.out.print("Lecture description: ");
this.lectureDescription = keyboard.nextLine();
System.out.print("Lecturer hourly rate ");
this.lecturerHourlyRate = keyboard.nextFloat();
System.out.print("Lecture hours amount: ");
this.lectureHoursAmount = keyboard.nextFloat();
this.lectureCost = this.lecturerHourlyRate * this.lectureHoursAmount;
System.out.println("The cost of the lecture " + this.lecturerName + " is $ " + this.lectureCost);
arrLecturesCostTotal.add(this.lecturerHourlyRate * this.lectureHoursAmount);
listLectures.add(this.lectureTitle + " by " + this.lecturerName);
}
}
}
As you can see, there are a lot of attributes to each class.
Then, I proceeded to create another class to create the objects using these setters (setConferenceData() and setDataLecture()).
public class Manager {
public static void main(String[] args) {
Conference conference01 = new Conference();
Lectures lectureSet = new Lectures();
Lectures.Lecture lecture01 = lectureSet.new Lecture();
Lectures.Lecture lecture02 = lectureSet.new Lecture();
conference01.setConferenceData();
lecture01.setDataLecture();
lecture02.setDataLecture();
lectureSet.getLecturesList();
lectureSet.getLecturesTotalCost();
}
}
So, one of the deliverables is a comparison between the lectures' costs. I need to return the most and the least expensive lectures (their costs and their names). However, I can't figure out how to do that because I don't know how to compare instances' attributes values. Specially because they're created by inputting data in the console.
My logic is probably wrong as I'm pretty much experimenting and crossing my fingers so I don't see an error in the console, but this is all I could come up with.
Could someone assist me, please?
Few tips here.
You probably should not call Scanner in you data classes. Instead call scanner in your main method and just feed the results to your classes through constructor or setters. This way you separate concerns and classes like Conference and Lecture don't need to know anything about your input method (scanner in this case).
Conference should contain lectures means that List<Lecture> should probably be field inside the class Conference among other fields.
Lecture should probably have two fields (among other stuff) double lengthHours and double hourlyCost. Then you could have a method in Lecture:
public double totalCost() {
return hourlyCost * lengthHours;
}
And then you could have a method in Conference:
public double totalCost() {
double lecturesTotal = 0.0;
for (Lecture lecture : lectures {
lecturesTotal += lecture.totalCost();
}
return lecturesTotal + //other stuff like conference managers pay;
}
Hope that gets you going in the right direction.

How do you store names in an Array using a loop? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I'm trying to write a program that prompt the user to enter the number of game players, the game players' names, their scores, and prints their scores' in decreasing order of their scores.
I need to do this using arrays for names and scores. Unfortunately this is all I have.
A sample output
Enter the number of players: n
Enter the name of the player: Ash
Enter the player's score: 1200
Enter the name of the player: Brock
Enter the player's score: 900
Enter the name of the player: Misty
Enter the player's score: 1300
Misty 1300.0
Ash 1200.0
Brock 900.0
import java. util.*;
public class HomeworkAssignment12 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of game players: ");
int numOfPlayers = input.nextInt();
String[] names = new String[numOfPlayers];
double[] scores = new double[numOfPlayers];
//Trying to store the names the user inputs into the names[] array
for ( int i = 0; i < names.length; i++) {
int index = i;
System.out.println("Enter a game players name: ");
names[index] = input.nextLine();
System.out.println("Enter the player's score: ");
scores[index] = input.nextDouble();
//used to check what the loop is doing each iteration
System.out.println(i);
}//end for
}//end main
}//end class
Your nearly there, the following code expands on your great attempt. As for your question of how to add the name into the array using an index? You can simply use the variable i from your for-loop.
(I have left out how to print the values from the two arrays in your desired format as an exercise for you):
import java.util.Scanner;
import java.util.Arrays;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of game players: ");
int numOfPlayers = scanner.nextInt();
String[] names = new String[numOfPlayers];
double[] scores = new double[numOfPlayers];
for (int i=0; i<names.length; i++){
System.out.print("Enter a players name: ");
String name = scanner.next();
names[i] = name;
System.out.print("Enter " + name +"\'s score: ");
while(scanner.hasNext()) {
if(scanner.hasNextDouble()) {
double score = scanner.nextDouble();
scores[i] = score;
break;
} else {
System.out.println("ERROR: Invalid Input");
System.out.print("Enter " + name +"\'s score: ");
scanner.next();
}
}
}
System.out.println("The names array: " + Arrays.toString(names));
System.out.println("The scores array: " + Arrays.toString(scores));
}
}
Exampe Usage:
Enter the number of game players: 2
Enter a players name: Max
Enter Max's score: 3
Enter a players name: John
Enter John's score: 6
The names array: [Max, John]
The scores array: [3.0, 6.0]
Try it here!

Displaying details of object arrays

Hi I'm very new to programming and I'm trying to write a programme in eclipse that does the following.
Create a Student class with 4 attributes: name, mark, course and phone number which are entered by the user.
Have a constructor which initialises those four attributes to the parameters passed in, and a display() method which displays the details of the Student.
Declares an empty array of 5 Student objects.
Create a Student object at the current position of the array using these variables.
Make a loop which calls the display() method of each Student in the array.
So far I've got the programme working to the point that it creates the array of 5 students and reads in the four different attributes from the user. But I can not figure out how to create a loop which calls the display method for each of the students.
This is my code so far..
import java.util.Scanner;
public class Student {
private String name, course;
private int mark, number;
public Student(String nameIn, String courseIn, int markIn, int numberIn)
{
this.name = nameIn;
this.course = courseIn;
this.mark = markIn;
this.number = numberIn;
}
public void display()
{
System.out.println("Name: " + this.name + " Course " + this.course + " mark: " + this.mark + " Number " + this.number);
}
public static void main (String[] args)
{
String[] Student = new String[5];
Scanner scanner = new Scanner(System.in);
for (int counter=0; counter< 5; counter++)
{
System.out.println("Enter name for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter course for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter mark for student " + counter);
Student[counter] = scanner.nextLine();
System.out.println("Enter number for student " + counter);
Student[counter] = scanner.nextLine();
}
for (int counter=0; counter< 5; counter++)
{
System.out.println(Student[counter].display());
}
}
}
PS sorry in advance if I have posted this question wrong. Its my first post and I couldn't find a similar question else where.
Thanks in advance.
Your current code doesn't create an array of Student, nor populate it correctly (each loop overwrites the former data) .
Also, the way you were calling display was wrong :
System.out.println(Student[counter].display());
First, you want to call display on an instance of Student, not on the class.
Second, you don't have to call System.out.println, because displayalready does this work (and calling System.out.println with the void parameter, because the display method returns nothing, will get you nowhere)
Try this way :
Student[] students = new Student[5];
for (int counter=0; counter< 5; counter++)
{
System.out.println("Enter name for student " + counter);
String name = scanner.nextLine();
System.out.println("Enter course for student " + counter);
String course = scanner.nextLine();
System.out.println("Enter mark for student " + counter);
String mark = scanner.nextLine();
System.out.println("Enter number for student " + counter);
String number = scanner.nextLine();
Student student = new Student(name, course, mark, number);
students[counter] = student;
}
for (int counter=0; counter< students.length; counter++)
{
students[counter].display();
}

for loop class assignment gone wrong

I'm in a class in college and we're doing Java. This is only my 4th class so I'm super new (be nice). My problem, hopefully my only one is that this will actually run but, after the user is asked to input the number of students grades you'd like to enter. It then goes into the for loop and asks the next two questions at the same time and then I get an error. I'm trying to figure out how to get it to ask the questions separately but I'm not having any luck. Someone had suggested io.console but I don't think we're allowed to use that, we haven't learned it yet. I came across hasNext but I'm not really sure how it works, and the more I read on it the more it confuses me.
Any help is greatly appreciated!
/*Write a java program that prompts the user to enter the number of students and then each student’s name and score,
* and finally displays the student with highest score and the student with the second- highest score.
* You are NOT allowed to use ‘Arrays’ for this problem (as we have not covered arrays yet).
*
* HINT: You do not need to remember all the inputs. You only need to maintain variables for max and second max
* scores and corresponding names. Whenever you read a new input, you need to compare it to the so far established
* max & second max scores and change things accordingly. */
import java.util.Scanner;
public class StudentScore {
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int count;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.print("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize.hasNext; i++) {
System.out.print("Please enter the students name? ");
studentName = scan.hasNextLine();
System.out.print("Please enter the students score? ");
score = scan.nextInt();
}
if (score >= secondHighScore) {
secondHighScore = highScore;
secondHighName = highName;
highScore = score;
highName = studentName;
}
}
System.out.print("Student with the highest score: " + highName + " " + highScore);
System.out.print("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}
}
First off you need to check if the recieved score is greater than the second score and if that score if greater than the highest score. Secondly replace studentName = scan.hasNextLine() with studentName = scan.nextLine(). Also create a new Scanner.
Code:
public static void main(String[] args) {
String studentName="", highName="", secondHighName="";
int score=0, highScore=0, secondHighScore=0;
int classSize;
Scanner scan = new Scanner(System.in);
System.out.println("How many students' grades do you want to enter? ");
classSize = scan.nextInt();
for (int i = 0; i < classSize; i++) {
System.out.println("Please enter the student #" + (i + 1) + "'s name? ");
//new Scanner plus changed to nextLine()
scan = new Scanner(System.in);
studentName = scan.nextLine();
System.out.println("Please enter the student #" + (i + 1) + " score? ");
score = scan.nextInt();
if(score >= highScore){
secondHighName = highName;
secondHighScore = highScore;
highName = studentName;
highScore = score;
} else if(score >= secondHighScore && score < highScore){
secondHighName = studentName;
secondHighScore = score;
}
}
scan.close();
System.out.println("Student with the highest score: " + highName + " " + highScore);
System.out.println("Student with the second highest score: " + secondHighName + " " + secondHighScore);
}

How to use loops and average in Java [duplicate]

This question already has answers here:
How to get average from given values
(3 answers)
Closed 9 years ago.
My program is supposed to find the average of female, male, and total average GPA of students. And also total female, male, and total students. First it asks if the student is male or female. If you choose male it does the loop, but after it ends. I want my program to go straight into the next choice. Example if you choose male the you'll input female and visa versa.
import java.util.Scanner;
public class practice {
public static void main(String [] args) {
Scanner keyboard = new Scanner (System.in);
int maleCount=0, femaleCount=0, totalStudents;
double GPA, mTotal = 0, mAverage, fTotal = 0, fAverage, allAverage;
System.out.println("Is the student Male or Female?");
System.out.println("Enter M for male or F for female.");
String student = keyboard.next().toUpperCase();
System.out.println("Enter GPA");
GPA = keyboard.nextDouble();
if (student.equals("M")) {
while (GPA >=0) {
mTotal = mTotal + GPA;
maleCount++;
GPA = keyboard.nextDouble();
}
}
if (student.equals("F")) {
while (GPA >=0) {
fTotal = fTotal + GPA;
femaleCount++;
GPA = keyboard.nextDouble();
}
}
mAverage = mTotal/maleCount;
fAverage = fTotal/femaleCount;
allAverage = mTotal + fTotal;
totalStudents = maleCount + femaleCount;
System.out.println("Total MALE students: " + maleCount);
System.out.println("Total FEMALE students: " + femaleCount);
System.out.println("Total STUDENTS: " + totalStudents);
System.out.println("Total MALE GPA: " + mTotal);
System.out.println("Total FEMALE GPA: " + fTotal);
System.out.println("Total MALE Average GPA: " + mAverage);
System.out.println("Total average: " + allAverage);
}
}
How to use loops and average in Java?
Well, pretty much as in the code in your question, I'd say. Just add a loop around the part that needs a loop, and figure out how you are going to end the looping.
The other problems that leap out at me are:
You seem to be accepting the input in a strange order.
You are calculating allAverage incorrectly. Just look at the code again. The problem should be obvious.
Actually, one of the difficulties with answering this Question is that it is not at all clear how the program as written is supposed to behave. And we can't infer that from what you've shown us. 'Cos what you've written obviously doesn't work ... from a usability perspective.
If you don't understand and can't explain the requirements properly, there is not much chance that you will be able to implement them correctly.
Fixed my code sorry for it being unclear.
import java.util.Scanner;
public class practice
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner (System.in);
int maleCount=0, femaleCount=0, totalStudents, count = 0;
double GPA, mTotal = 0, mAverage, fTotal = 0, fAverage, allAverage;
System.out.println("Is the student Male or Female?");
System.out.println("Enter M for male or F for female.");
String student = keyboard.next().toUpperCase();
do{
System.out.println("Enter GPA " + student);
GPA = keyboard.nextDouble();
if (student.equals("M"))
{
while (GPA >=0)
{
mTotal = mTotal + GPA;
maleCount++;
GPA = keyboard.nextDouble();
}
student = "F";
}
else if (student.equals("F"))
{
while (GPA >=0)
{
fTotal = fTotal + GPA;
femaleCount++;
GPA = keyboard.nextDouble();
}
student = "M";
}
}
while (++count < 2);
mAverage = mTotal/maleCount;
fAverage = fTotal/femaleCount;
totalStudents = maleCount + femaleCount;
allAverage = (mTotal + fTotal)/totalStudents;
System.out.println("Total MALE students: " + maleCount);
System.out.println("Total FEMALE students: " + femaleCount);
System.out.println("Total STUDENTS: " + totalStudents);
System.out.println("Total MALE GPA: " + mTotal);
System.out.println("Total FEMALE GPA: " + fTotal);
System.out.println("Total average: " + allAverage);
}

Categories