displays the student with the highest score - java

Write a program that prompts the user to enter the number of students and each student’s name and score, and finally displays the student with the highest score.
I stuck at how do I display their name?
Here's my code:
package Exercises;
import java.util.Scanner;
public class Page93
{
public static void main(String[] args)
{
String name = null;
int count;
double score = 0;
double highest = 0;
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of student : ");
int numberofstudent = input.nextInt();
for (count=0; count<numberofstudent; count++)
{
System.out.print("\nStudent name : ");
name = input.next().toUpperCase();
System.out.print("Score : ");
score = input.nextInt();
if (highest<score)
highest=score;
}
System.out.print("\nThe highest score : " + highest );
}
}

Define a variable studentWithHighestScore to store Student with the highest score. Update this variable whenerver you update highest.
if (highest<score) {
highest=score;
studentWithHighestScore = name
}

package Exercises;
import java.util.Scanner;
public class Page93
{
public static void main(String[] args)
{
String name = null;
int count;
double score = 0;
double highest = 0;
String highestName;
Scanner input = new Scanner (System.in);
System.out.print("Enter the number of student : ");
int numberofstudent = input.nextInt();
for (count=0; count<numberofstudent; count++)
{
System.out.print("\nStudent name : ");
name = input.next().toUpperCase();
System.out.print("Score : ");
score = input.nextInt();
if (highest<score)
{
highest=score;
highestName = name;
}
}
System.out.print("\nThe highest student : " + highestName + " score : " + highest );
}
}

import java.util.Scanner;
class Student {
String name;
String stu_id;
int score;
public Student() {
}
public Student(String initName, String initId, int initScore) {
name = initName;
stu_id = initId;
score = initScore;
}
}
class accept {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input number of students:");
int n = Integer.parseInt(in.nextLine().trim()) ;
System.out.println("Input Student Name, ID, Score :");
Student stu = new Student();
Student max = new Student();
Student min = new Student("","", 0);
String [] arr1=new String [n];
String [] arr2=new String [n];
int [] arr3=new int [n];
for (int i = 0; i < n; i ++) {
arr1[i]=in.next();
arr2[i]=in.next();
arr3[i]=in.nextInt();
stu.name = arr1[i];
stu.stu_id = arr2[i];
stu.score = arr3[i];
if (max.score < stu.score) {
max.name = stu.name;
max.stu_id = stu.stu_id;
max.score = stu.score; }}
for(int j = 0; j < n; j ++){
stu.name = arr1[j];
stu.stu_id = arr2[j];
stu.score = arr3[j];
if (min.score < stu.score&&stu.score!=max.score) {
min.name = stu.name;
min.stu_id = stu.stu_id;
min.score = stu.score;
}
}
System.out.println("name, ID of the highest score and the second highest score:");
System.out.println(max.name + " " + max.stu_id);
System.out.println(min.name + " " + min.stu_id);
in.close();
}
}

Related

How do you connect a single scanner to two arrays?

Basically, I'm trying to ask the user's input and the input should store in two arrays using a single scanner. Using two would ask the user twice and that would be impractical. The code looks like this
int record = 0;
Scanner midOrFinal = new Scanner(System.in);
Scanner scansubjects = new Scanner(System.in);
Scanner scangrades = new Scanner(System.in);
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
record = midOrFinal.nextInt();
int midterm[] = new int[8];
int grades[] = new int[8];
{
if ( record == 1 )
System.out.println("Enter 8 subjects and their corresponding grades:");
System.out.println();
int i = 0;
for( i = 0; i < 8; i++ )
{
System.out.println(subjects[i]);
System.out.print("Enter Grade: ");
grades[i] = scangrades.nextInt();
if( i == ( subjects.length) )
System.out.println();
}
System.out.println("Enter Grade Successful");
}
If the user chooses option 1, the user will be given some subjects in an array (which I didn't include) and asked to input the grades. The input shall then proceed to the midterm OR finalterm array but I can't seem to do it by using one scanner.
If there are better ideas than my proposed idea, then please share. I'm still very new in Java and my first time using stackoverflow. Thanks!
Break out the grade collection into a new function, and pass along the array you want to collect the grades into.
public static void main(String[] args) throws IOException {
int gradeType = 0;
// Use a single scanner for all input
Scanner aScanner = new Scanner(System.in);
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
gradeType = aScanner.nextInt();
String[] subjects = { "Subject A", "Subject B" };
int[] midtermGrades = new int[subjects.length];
int[] finalGrades = new int[subjects.length];
int[] gradesToCollect;
// Use gradesToCollect to reference the array you want to
// collect into.
//
// Alternatively, we could call collectGrades() in both the if/else
// condition
if (gradeType == 1) {
gradesToCollect = midtermGrades;
} else {
gradesToCollect = finalGrades;
}
collectGrades(subjects, gradesToCollect, aScanner);
System.out.println("\n\nThese are the collected grades");
System.out.println("Mid Final");
for (int i = 0; i < subjects.length; i++) {
System.out.format("%3d %3d\n", midtermGrades[i], finalGrades[i]);
}
}
// Collect a grade for each subject into the given grades array.
public static void collectGrades(final String[] subjects, final int[] grades, Scanner scn) {
System.out.format("Enter %s subjects and their corresponding grades:",
subjects.length);
System.out.println();
for (int i = 0; i < subjects.length; i++) {
System.out.format("Enter Grade for %s : ", subjects[i]);
grades[i] = scn.nextInt();
if (i == (subjects.length))
System.out.println();
}
System.out.println("Enter Grade Successful");
}
class Main {
public static final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
in.useDelimiter("\r?\n");
Student student = new Student();
System.out.println("Press 1 to Record for Midterm");
System.out.println("Press 2 to Record for Final Term");
int record = in.nextInt();
if (record == 1) {
student.setTerm(TermType.MID);
System.out.println("Enter 8 subjects and their corresponding grades:");
System.out.println("Enter Subject and grades space separated. Example - \nMaths 79");
System.out.println();
for (int i = 0; i < 8; i++) {
System.out.println("Enter Subject " + (i + 1) + " details");
String subjectAndGrade = in.next();
int index = subjectAndGrade.lastIndexOf(" ");
String subject = subjectAndGrade.substring(0, index);
int grade = Integer.parseInt(subjectAndGrade.substring(index + 1));
student.getSubjects().add(new Subject(grade, subject));
}
System.out.println("Enter Grade Successful");
System.out.println("========================================================");
System.out.println("Details: ");
System.out.println("Term Type " + student.getTerm());
for(int i = 0; i< student.getSubjects().size(); i++) {
System.out.println("Subject: " + student.getSubjects().get(i).getSubjectName() + ", Grade: " + student.getSubjects().get(i).getGradeScore());
}
}
}
}
class Student {
private List<Subject> subjects = new ArrayList<>();
private TermType term;
public List<Subject> getSubjects() {
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
public TermType getTerm() {
return term;
}
public void setTerm(TermType term) {
this.term = term;
}
}
class Subject {
private int gradeScore;
private String subjectName;
public Subject(int gradeScore, String subjectName) {
this.gradeScore = gradeScore;
this.subjectName = subjectName;
}
public double getGradeScore() {
return gradeScore;
}
public void setGradeScore(int gradeScore) {
this.gradeScore = gradeScore;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
}
scanners work by separating the input into a sequence of 'tokens' and 'delimiters'. Out of the box, 'one or more whitespace characters' is the delimiter.

Java how to get and show simple data

I need to get data and show it.
This is my question
Construct a class designed to perform that takes student record containing Roll Number, Name and Marks
as data and functions like get()and show() to take input in data and display data.
I am trying to do like this
import java.util.Scanner;
class Student {
String name;
String stu_id;
int score;
public Student() {
this(" ", " ", 0);
}
public Student(String initName, String initId, int initScore) {
name = initName;
stu_id = initId;
score = initScore;
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input number of students:");
int n = Integer.parseInt(in.nextLine().trim());
System.out.println("Input Student Name, ID, Score:");
Student stu = new Student();
for (int i = 0; i < n; i ++) {
stu.name = in.next();
stu.stu_id = in.next();
stu.score = in.nextInt();
System.out.println(stu.name + " " + stu.stu_id);
}
System.out.println("name, ID of the highest score and the lowest score:");
System.out.println(stu.name + " " + stu.stu_id);
in.close();
}
}
But its wrong I just need to create a function show() on which ill get data and from get() function it will just print
It seems to me that this solution is acceptable, you will try to rewrite it later from memory, this is how I began to learn to program.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Student {
String name;
String stu_id;
int score;
public Student() {
this("None", "None", 0);
}
public Student(String initName, String initId, int initScore) {
name = initName;
stu_id = initId;
score = initScore;
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", stu_id='" + stu_id + '\'' +
", score=" + score +
'}';
}
}
public class Main {
public static Student get(Scanner in) {
System.out.println("Input Student Name, ID, Score:");
String name = in.next();
int score = in.nextInt();
String stu_id = in.next();
return new Student(name, stu_id, score);
}
public static void show(Student student) {
System.out.println(student);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input number of students:");
int n = Integer.parseInt(in.nextLine().trim());
List<Student> studentList = new ArrayList<>();
for (int i = 0; i < n; i ++) {
Student stu = get(in);
studentList.add(stu);
}
studentList.forEach(student -> {show(student);});
in.close();
}
}
import java.util.Scanner;
class Student {
String name;
String stu_id;
int score;
Scanner in = new Scanner(System.in);
public void get()
{
System.out.println("Enter Student Name, ID, Score:");
name = in.nextLine();
stu_id = in.nextLine();
score = in.nextInt();
}
public void show()
{
System.out.println("Name: "+name+"\nId: "+stu_id+"\nScore: "+score);
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input number of students:");
int n = in.nextInt();
in.nextLine();
Student[] stu = new Student[n];
for (int i = 0; i < n; i++) {
stu[i] = new Student();
stu[i].get();
}
for (int i = 0; i < n; i++) {
stu[i].show();
}
in.close();
}
}

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

how to print out a string of names and numbers from an array

I have to make a program where you ask user to enter any number of students, that asks the name and grade of each student. So if I said 2 students, I would put billy smith, then 54, then it would ask me the name of the 2nd student, john smith, then the grade, 81. Then it outputs the names with grades in descending order of grades. It would output:
name---------grades
------------------
John smith 81
billy smith 54
I have evrything except for it printing it out. I need it to print out the name with the grade. Here is what I have:
import java.util.*;
public class assignment5 {
public static void main(String[] args) {
// Scanner for first name and last name with space in between.
java.util.Scanner input = new java.util.Scanner(System.in);
input.useDelimiter(System.getProperty("line.separator"));
System.out.print("Enter the number of students: ");
int numofstudents = input.nextInt();
String[] names = new String[numofstudents];
Double[] array = new Double[numofstudents];
for(int i = 0; i < numofstudents; i++) {
System.out.print("Enter the student's name: ");
names[i] =input.next();
System.out.print("Enter the student's score: ");
array[i] = (Double) input.nextDouble();
}
System.out.print("Name" + "\tScore");
System.out.print("\n----" + "\t----\n");
selectionSort(names, array);
System.out.println(Arrays.toString(names));
}
public static void selectionSort(String[] names, Double[] array) {
for(int i = array.length - 1; i >= 1; i--) {
String temp;
Double currentMax = array[0];
int currentMaxIndex = 0;
for(int j = 1; j <= i; j++) {
if (currentMax > array[j]) {
currentMax = array[j];
currentMaxIndex = j;
}
}
if (currentMaxIndex != i) {
temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
array[currentMaxIndex] = array[i];
array[i] = currentMax;
}
}
}
}
This is very similar to value base sorted map. The below provided solution would be helpful.
Sort a Map<Key, Value> by values (Java)
This is one way to do it, create a Student class to store name/grade pairs, and use Arrays.sort() with a custom Comparator to sort in descending order after all the input is read:
import java.util.*;
public class assignment5 {
public static void main(String[] args) {
// Scanner for first name and last name with space in between.
java.util.Scanner input = new java.util.Scanner(System.in);
input.useDelimiter(System.getProperty("line.separator"));
System.out.print("Enter the number of students: ");
int numofstudents = input.nextInt();
//String[] names = new String[numofstudents]; //not needed
//Double[] array = new Double[numofstudents]; //not needed
Student[] students = new Student[numofstudents]; //added
for(int i = 0; i < numofstudents; i++) {
System.out.print("Enter the student's name: ");
//names[i] =input.next();
String student = input.next(); //added
System.out.print("Enter the student's score: ");
//array[i] = (Double) input.nextDouble();
Double grade = (Double) input.nextDouble(); //added
students[i] = new Student(student, grade); //added
}
System.out.print("Name" + "\tScore");
System.out.print("\n----" + "\t----\n");
//selectionSort(names, array);
Arrays.sort(students, new Comparator<Student>() {
#Override
public int compare(Student entry1, Student entry2) {
return entry2.grade.compareTo(entry1.grade); //sort by grade in descending order
}
});
//System.out.println(Arrays.toString(students));
for (int i = 0; i < students.length; i++){
System.out.println(students[i].student + "\t" + students[i].grade);
}
}
}
public class Student{
public String student;
public Double grade;
public Student(String s, Double g){
this.student = s;
this.grade = g;
}
}

multiple prints for each input. Why?

Each time I run this code it gets to where it asks for student id and it prints out the student id part and the homework part. Why? I am trying to do get a string for name, id, homework, lab, exam, discussion, and project then in another class I am splitting the homework, lab, and exam strings into arrays then parsing those arrays into doubles. After I parse them I total them in another method and add the totals with project and discussion to get a total score.
import java.util.Scanner;
import java.io.*;
public class GradeApplication_Kurth {
public static void main(String[] args) throws IOException
{
Student_Kurth one;
int choice;
boolean test = true;
do
{
Scanner keyboard = new Scanner(System.in);
PrintWriter outputFile = new PrintWriter("gradeReport.txt");
System.out.println("Please select an option: \n1. Single Student Grading \n2. Class Grades \n3. Exit");
choice = keyboard.nextInt();
switch (choice)
{
case 1 :
System.out.println("Please enter your Student name: ");
String name = keyboard.next();
System.out.println("Please enter you Student ID: ");
String id = keyboard.nextLine();
System.out.println("Please enter the 10 homework grades seperated by a space: ");
String homework = keyboard.next();
System.out.println("Please enter the 6 lab grades seperated by a space: ");
String lab = keyboard.nextLine();
System.out.println("Please enter the 3 exam grades seperated by a space: ");
String exam = keyboard.nextLine();
System.out.println("Please enter the discussion grade: ");
double discussion = keyboard.nextDouble();
System.out.println("Please enter the project grade: ");
double project = keyboard.nextDouble();
one = new Student_Kurth(name, id, homework, lab, exam, discussion, project);
outputFile.println(one.toFile());
System.out.println(one);
break;
case 2 :
File myFile = new File("gradeReport.txt");
Scanner inputFile = new Scanner(myFile);
while(inputFile.hasNext())
{
String str = inputFile.nextLine();
System.out.println("\n" + str);
}
break;
case 3 :
test = false;
keyboard.close();
outputFile.close();
System.exit(0);
}
} while (test = true);
}
}
second class
public class Student_Kurth
{
public String homework;
public String name;
public String id;
public String lab;
public String exam;
public double project;
public double discussion;
public double[] hw = new double[10];
public double[] lb = new double[6];
public double[] ex = new double[3];
public final double MAX = 680;
public double percentage;
public String letterGrade;
public Student_Kurth()
{
homework = null;
name = null;
id = null;
lab = null;
exam = null;
project = 0;
discussion = 0;
}
public Student_Kurth(String homework, String name, String id, String lab, String exam, double project, double discussion)
{
this.homework = homework;
this.name = name;
this.id = id;
this.lab = lab;
this.exam = exam;
this.project = project;
this.discussion = discussion;
}
public void Homework(String homework)
{
String delims = " ";
String[] tokens = this.homework.split(delims);
int tokenCount = tokens.length;
for(int i = 0; i < tokenCount; i++)
{
hw[i] = Double.parseDouble(tokens[i]);
}
}
public void Lab(String lab)
{
String delims = " ";
String[] tokens = this.lab.split(delims);
int tokenCount = tokens.length;
for(int i = 0; i < tokenCount; i++)
{
lb[i] = Double.parseDouble(tokens[i]);
}
}
public void Exam(String exam)
{
String delims = " ";
String[] tokens = this.exam.split(delims);
int tokenCount = tokens.length;
for(int i = 0; i < tokenCount; i++)
{
ex[i] = Double.parseDouble(tokens[i]);
}
}
public double getHomeworkTotal(double[] hw)
{
double hwTotal = 0;
for(int i = 0; i < hw.length; i++)
{
hwTotal += hw[i];
}
return hwTotal;
}
public double getLabTotal(double[] lb)
{
double lbTotal = 0;
for(int i = 0; i < lb.length; i++)
{
lbTotal += lb[i];
}
return lbTotal;
}
public double getExamTotal(double[] ex)
{
double exTotal = 0;
for(int i = 0; i < ex.length; i++)
{
exTotal += ex[i];
}
return exTotal;
}
public double getTotalScores(double getExamTotal, double getLabTotal, double getHomeworkTotal)
{
return getExamTotal + getLabTotal + getHomeworkTotal + this.project + this.discussion;
}
public double getPercentage(double getTotalScores)
{
return 100 * getTotalScores / MAX;
}
public String getLetterGrade(double getPercentage)
{
if(getPercentage > 60)
{
if(getPercentage > 70)
{
if(getPercentage > 80)
{
if(getPercentage > 90)
{
return "A";
}
else
{
return "B";
}
}
else
{
return "C";
}
}
else
{
return "D";
}
}
else
{
return "F";
}
}
public void getLetter(String getLetterGrade)
{
letterGrade = getLetterGrade;
}
public void getPercent(double getPercentage)
{
percentage = getPercentage;
}
public String toFile()
{
String str;
str = " " + name + " - " + id + " - " + percentage + " - " + letterGrade;
return str;
}
public String toString()
{
String str;
str = "Student name: " + name + "\nStudent ID: " + id + "\nTotal Score: " + getTotalScores(getExamTotal(ex), getLabTotal(lb), getHomeworkTotal(hw)) +
"\nMax Scores: " + MAX + "Percentage: " + percentage + "Grade: " + letterGrade;
return str;
}
}
At the end of the switch, you have
while ( test = true)
You probably want to change that to
while ( test == true)
Also, take these lines out of the loop:
Scanner keyboard = new Scanner(System.in);
PrintWriter outputFile = new PrintWriter("gradeReport.txt");
In addition to Ermir's answer, this line won't capture all the grades:
System.out.println("Please enter the 10 homework grades seperated by a space: ");
String homework = keyboard.next();
Keyboard.next only reads until the next delimiter token, so if you want to capture 10 grades separated by spaces you need capture the whole line, like:
System.out.println("Please enter the 10 homework grades separated by a space: ");
String homework = keyboard.nextLine();

Categories