Java highest score - java

Okay so i'm trying to make a program to display the top 2 highest scorers of 5 students only.
So sample output.
Enter your name : Spear
Enter score : 56
Enter your name : Sky
Enter score : 61
Enter your name : Spy
Enter score : 45
Enter your name : Raks
Enter score : 31
Enter your name : Felicio
Enter score : 39
Congratulations Sky!
Congratulations Spear!
I only know how to take the largest score and not the second here is what i got so far.
import java.util.Scanner;
public class Highest{
public static void main(String[]args) {
Scanner x = new Scanner(System.in);
String name = "";
int score;
int k;
int highest = 0;
num = x.nextLine();
largest = num;
for (int i = 0; i <= 5; i++) {
System.out.print("Enter name: ");
k = x.nextInt();
System.out.print("Enter score: ");
num = x.nextInt();
if (num > highest) {
highest = num;
}
}
System.out.println(largest);
}
} // how do i display the name of the highest score and the second placer?

You may want to look at sorting methods to solve such problems in the future e.g. sorting Arrays and sorting collections
For your particular case where you want to select the two max elements you can simply use two variables
int highestScore = 0;
String highestName = "";
int secondScore = 0;
String secondName = "";
and then
if (num > highestScore) {
secondScore = highestScore;
secondName = highestName;
highestScore = num;
highestName = name;
} else if (num > secondScore) {
secondScore = num;
secondName = name;
}
The code may be cleaner if you define a Student class to hold score and name.
Printing is straightforward
System.out.printnl("Congratulations " + highestName + "!");
System.out.printnl("Congratulations " + secondName + "!");

To expand on what Manos said:
You probably want to create a class for your students:
class Student {
private String name;
private int score;
Student(String name, int score) {
this.name = name;
this.score = score;
}
public int getScore() {
return this.score;
}
public String getName() {
return this.name;
}
}
You can then add each student to a collection and use a Comparator to sort your students:
Collections.sort(students, new Comparator<Student>() {
public int compare(Student o1, Student o2) {
return Integer.compare(o1.getScore(), o2.getScore());
}
});
The resulting collection will hold a list where the highest scoreing students will be at the far end of the collection, or you can then reverse the collection so they are at the begining instead:
Collections.reverse(students);
Full example:
public static void main(String[] args) {
class Student {
private String name;
private int score;
Student(String name, int score) {
this.name = name;
this.score = score;
}
public int getScore() {
return this.score;
}
public String getName() {
return this.name;
}
}
ArrayList<Student> students = new ArrayList<>();
for (int i = 0; i < 10; i++) {
java.util.Random rand = new java.util.Random();
Student s = new Student("Student " + i, rand.nextInt());
students.add(s);
}
Collections.sort(students, new Comparator<Student>() {
public int compare(Student o1, Student o2) {
return Integer.compare(o1.getScore(), o2.getScore());
}
});
Collections.reverse(students);
System.out.println("Highest scoring student: " + students.get(0).getName() + " with a score of " + students.get(0).getScore());
System.out.println("Highest scoring student: " + students.get(1).getName() + " with a score of " + students.get(1).getScore());
// List all students (Java 8 only...)
students.forEach( x -> System.out.println("Name: " + x.getName() + " with score: " + x.getScore()) );
}

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();
}
}

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.

Selection sort a roster

So I'm supposed to create a program that asks for the class size. Then using that size, you enter a students name and score until you fill the class size. After doing that, I'm supposed to invoke a selectionSort method to sort the scores in descending order. So the output is essentially a table. One column is name, the other is score and the scores are supposed to be in descending order with their appropriate name. I have most of the program down, I just can't figure out how to tie the students name to their score that was entered. Can someone steer me in the right direct? I'm at a loss. Here is my program:
import java.util.Scanner;
public class Roster {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
input.useDelimiter(System.getProperty("line.separator"));
System.out.print("Enter the size of the class: ");
int size = input.nextInt();
double[]score = new double[size];
String[]name = new String[size];
for(int i = 0; i < size; i++){
System.out.print("Please enter a student name: ");
String n = input.next();
name[i] = n;
System.out.print("Please enter " + n + "'s score: ");
double s = input.nextDouble();
score[i] = s;
System.out.println();
}
selectionSort(score,name);
System.out.print("THe class size is: " + size + "\n");
System.out.print("Name Score\n");
System.out.print("---- -----\n");
for(int i = 0; i < name.length; i++)
System.out.println(name[i] + " " + score[i] + " ");
System.out.println();
}
public static void selectionSort(double[] score, String[] name){
for(int i = score.length-1; i > 0; i--){
int maxIndex = 0;
for(int j = 1; j <= i; j++)
if(score[j] < score[maxIndex])
maxIndex = j;
double temp = score[i];
score[i] = score[maxIndex];
score[maxIndex] = temp;
}
}
}
I already commented a simple solution, but really the best thing to do would be to create a class of roster entries:
public class RosterEntry {
private String name;
private double score;
/*Accessors and Mutators*/
}
Then in your main you can maintain a list or array of RosterEntrys so that when you make swaps in the selection sort, you swap RosterEntrys instead of scores and names individually.
You could create a class of pairs, which you store in an array. As such:
public class MyPair
{
private final String name;
private final Double score;
public MyPair(String aName, Double aScore)
{
name= aName;
score = aScore;
}
public String getName() { return name; }
public Double getScore() { return score; }
}
You can then create a simple array of type MyPair,
MyPair[] pupils = new MyPair(20);
You can access details of pupils by
pupils[i].getName;
or
pupils[i].getScore;

object array index value is being overided by the preceding index value

This is an odd situation for me, I just started learning Java OOP.
I made a class looks like this
public class Student {
public static String name;
public static int marks;
public Student(String n, int m){
name = n;
marks = m;
}
public static void printProperties(){
System.out.println("Name = " + name + " , marks = " + m);
}
}
As you can see the constructor accepts two data: name and marks.
in my main method
System.out.println("Please enter number of students:");
int n = scan.nextInt();
Student[] stu = new Student[n];
String name;
int marks = 0;
for(int i = 0; i < stu.length; i++){
System.out.println("Please enter name for student #" + (i+1));
name = scan.next();
System.out.println("Please enter marks for student #" + (i+1));
marks = scan.nextInt();
stu[i] = new Student(name,marks);
System.out.println();
}
//Display
for(int x = 0; x < stu.length; x++){
System.out.println("#" + (x+1) + " Name: " + stu[x].name + ", Marks: " + stu[x].marks);
}
So my output as follows:
Please enter number of students:
2
Please enter name for student #1
tom
Please enter age for student #1
20
Please enter name for student #2
billy
Please enter age for student #2
80
#1 Name: billy, Marks: 80
#2 Name: billy, Marks: 80
It should be:
#1 Name: tom, Marks: 20
#2 Name: billy, Marks: 80
Why is the preceding index value overidding its previous index value?
You code should work absolutely fine, if your Student class looks something like this :
public class Student{
String name;
int marks;
public Student(String name, int marks){
this.name = name;
this.marks = marks;
}
}
EDITED :
This is what Jon Skeet mentioned.
You are using static variables which are class level variables, so they are overridden every time you assign value to them and only the last value is retained.
You need instance variables here.
Do not make your fields static, and let's use private to control access -
public class Student {
private String name; // not static, and use private.
private int marks;
public Human(String n, int m){
name = n;
marks = m;
}
public void printProperties(){ // also should not be static.
System.out.println("Name = " + name + " , marks = " + m);
}
}
Don't use static , simple as that
A static variable belongs to the entire class. It is one variable that is shared among all of the objects. So when you change that variable, it changes it for all the objects.
Instead, define name and marks as instance variables. In other words, remove the static modifier from your variable declarations. An instance variable is unique to each object. Each object has its own copy of an instance variable.
Also, it's good practice to declare name and marks as private. Then create getters and setters for those variables. This hides the implementation.
import java.util.Scanner;
public class Student{
private String name;
private int marks;
public String getName() { //getter
return name;
}
public void setName(String name) { //setter
this.name = name;
}
public int getMarks() { //getter
return marks;
}
public void setMarks(int marks) { //setter
this.marks = marks;
}
public Student(String n, int m){
name = n;
marks = m;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter number of students:");
int n = scan.nextInt();
Student[] stu = new Student[n];
String name;
int marks = 0;
for(int i = 0; i < stu.length; i++){
System.out.println("Please enter name for student #" + (i+1));
name = scan.next();
System.out.println("Please enter marks for student #" + (i+1));
marks = scan.nextInt();
stu[i] = new Student(name,marks);
System.out.println();
}
//Display
for(int x = 0; x < stu.length; x++){
System.out.println("#" + (x+1) + " Name: " + stu[x].getName() + ", Marks: " + stu[x].getMarks());
}
scan.close();
}
}

Categories