Sorting the User input in Java - java

I am beginner in Java. I need help to proceed my code. Thanks in advance.
Question: Given a unsorted list of 5 athletes nominated for the coaching class, provide a way for the coach to search for the athlete name and provide grades. Finally print the list of athletes’ names with their grade in the sorted order of their names. Search for the athlete with highest grade.
package student;
import java.util.Scanner;
public class Atheletes {
String name;
static String grade,grade1,grade2,grade3,grade4;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of athelete1 and grade");
grade1 = in.nextLine();
Scanner ino = new Scanner(System.in);
System.out.println("Enter the name of athelete2 and grade");
grade2 = ino.nextLine();
Scanner ine = new Scanner(System.in);
System.out.println("Enter the name of athelete3and grade");
grade3 = ine.nextLine();
Scanner inp = new Scanner(System.in);
System.out.println("Enter the name of athelete4 and grade");
grade4 = inp.nextLine();
}
}

I have simplified your code and added comments as necessary.
// number of Athletes you want
Athlete[] eAthlete = new Athlete[5];
// Name of each athlete
String[] names = { "ss", "aa", "bb", "cc", "xx" };
// On each iteration, the name of the Athlete
// and his/her grade is set,
Scanner in = new Scanner(System.in);
for (int i = 0; i < eAthlete.length; i++) {
eAthlete[i] = new Athlete();
eAthlete[i].setName(names[i]);
System.out.println("Please enter Grade for: "
+ eAthlete[i].getName());
eAthlete[i].setGrade(in.nextLine());
}
in.close();
// Print all athletes with their grades,
System.out.println("Before Sorting");
for (Athlete s : eAthlete) {
System.out.println(s.getName() + " " + s.getGrade());
}
At this point, the grades and names are assigned to each athlete,
Output
Before Sorting
ss 123
aa 65465
bb 4654
cc .0231
xx 23123
Now we need to sort these Athletes based on their names.
We could have designed our own Comparator but since, you are not allowed to use Collections.sort, we would use rather poor approach i.e bubble sorting,
String tempStr;
for (int t=0; t<eAthlete.length-1; t++)
{
for (int i= 0; i < eAthlete.length - t -1; i++)
{
if(eAthlete[i+1].getName().compareTo(eAthlete[i].getName())<0)
{
tempStr = eAthlete[i].getName();
eAthlete[i].setName(eAthlete[i+1].getName());
eAthlete[i+1].setName(tempStr);
}
}
}
Printing the sorted athletes with their grades,
System.out.println("After Sorting");
for (Athelete s : eAthelete){
System.out.println(s.getName() + " " + s.getGrade());
}
Output:
After Sorting
aa 65465
bb 4654
cc .0231
ss 123
xx 23123
observe the names in above output.
here is your Athlete class,
class Athlete {
private String name;
private String grade;
public void setName(String name) {
this.name = name;
}
public void setGrade(String gr) {
grade = gr;
}
public String getGrade() {
return grade;
}
public String getName() {
return name;
}
}
Here is the complete code,
public class Main {
public static void main(String[] args) {
Athlete[] eAthlete = new Athlete[5];
String[] names = { "ss", "aa", "bb", "cc", "xx" };
Scanner in = new Scanner(System.in);
for (int i = 0; i < eAthlete.length; i++) {
eAthlete[i] = new Athlete();
eAthlete[i].setName(names[i]);
System.out.println("Please enter Grade for: "
+ eAthlete[i].getName());
eAthlete[i].setGrade(in.nextLine());
}
in.close();
// Print all athletes with their grades,
System.out.println("Before Sorting");
for (Athlete s : eAthlete) {
System.out.println(s.getName() + " " + s.getGrade());
}
String tempStr;
for (int t = 0; t < eAthlete.length - 1; t++) {
for (int i = 0; i < eAthlete.length - t - 1; i++) {
if (eAthlete[i + 1].getName().compareTo(eAthlete[i].getName()) < 0) {
tempStr = eAthlete[i].getName();
eAthlete[i].setName(eAthlete[i + 1].getName());
eAthlete[i + 1].setName(tempStr);
}
}
}
System.out.println("After Sorting");
for (Athlete s : eAthlete) {
System.out.println(s.getName() + " " + s.getGrade());
}
}
}
class Athlete {
private String name;
private String grade;
public void setName(String name) {
this.name = name;
}
public void setGrade(String gr) {
grade = gr;
}
public String getGrade() {
return grade;
}
public String getName() {
return name;
}
}

public class Athletes {
private String name;
private String grade;
public Athletes(String name, String grade) {
this.name = name;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
#Override
public String toString() {
return "Athletes [name=" + name + ", grade=" + grade + "]";
}
public static void main(String[] args) {
List<Athletes> lijst = new ArrayList<Athletes>();
lijst.add(new Athletes("bbb", "Grade1"));
lijst.add(new Athletes("ccc", "Grade2"));
lijst.add(new Athletes("aaa", "Grade3"));
lijst.add(new Athletes("ddd", "Grade4"));
Collections.sort(lijst, new Comparator<Athletes>() {
#Override
public int compare(Athletes o1, Athletes o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (Athletes athletes : lijst) {
System.out.println(athletes);
}
}
}

You may write your own comparator Class to sort the Athelete on basis of their names
public class AtheleteComparator implements Comparator
{
#override
public int compare(Atheletes first,Atheletes second)
{
return first.name.compareTo(second.name);
}
}
Then simply use
Collections.sort(List<Athelete>list,Your own Comparator's object)
To find out athelete with highest grade write another comparator which compares grades
then use
Collections.sort(arrayList,Comparator); // Sort the arraylist
arrayList.get(arrayList.size() - 1); //gets the last item, largest for an ascending sort

Ok, since you can use arrays and for loops but not collections:
public class Sorter(){
private int[] grades = {7, 6, 4, 10, 8};
private String[] names = {"John", "Erik", "Bob", "Frank", "Judy"};
public static void main(String args[]) {
new Sorter();
}
public Sorter(){
int[] tempGrades = {0, 0, 0, 0, 0};
String[] tempNames = {"", "", "", "", ""};
for (int x = 0; x < tempGrades.length; x++) {
if (grades[x] < tempGrades[1]) {
tempGrades[0] = grades[x];
tempNames[0] = names[x];
} else if (grades[x] < tempGrades[2]) {
tempGrades[0] = tempGrades[1];
tempGrades[1] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = names[x];
} else if (grades[x] < tempGrades[3]) {
tempGrades[0] = tempGrades[1];
tempGrades[1] = tempGrades[2];
tempGrades[2] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = tempNames[2];
tempNames[2] = names[x];
} else if (grades[x] < tempGrades[4]) {
tempGrades[0] = tempGrades[1];
tempGrades[1] = tempGrades[2];
tempGrades[2] = tempGrades[3];
tempGrades[3] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = tempNames[2];
tempNames[2] = tempNames[3];
tempNames[3] = names[x];
} else {
tempGrades[0] = tempGrades[1];
tempGrades[1] = tempGrades[2];
tempGrades[2] = tempGrades[3];
tempGrades[3] = tempGrades[4];
tempGrades[4] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = tempNames[2];
tempNames[2] = tempNames[3];
tempNames[3] = tempNames[4];
tempNames[4] = names[x];
}
}
grades = tempGrades;
names = tempNames;
for (int x = 0; x < grades.length; x++) {
System.out.println(tempNames[x] + " " + tempGrades[x]);
}
}
}
just for the future:
you can use an ArrayList<Athlete> where Athlete is a class that accepts (String name, int grade) as constructor paramaters and sorts athletes by grade by implementing its own comparator or you can use a LinkedHashMap<Integer, String> that sorts values by Key<Integer>.
Note: Class names with plural like Athletes are best used for Singleton classes that only implement static methods and variables. Always name classes by function (in this case sorting), AthleteSorter is also viable.

Related

Is there another way to get the index without using the index of the array? ex. Not using Array[5]

So, I was wondering if there is any way to get the Highest Name without using Names[5] ?
int[] points = { 68, 87, 91, 30, 56, 99, 91 };
String[] Names = { "Billon", "Bob", "Barbie", "Beny", "Bardon", "Becks", "Benji" };
showHighest(scores, Names);
int a = findThatName(Names, "Benji");
if (a == -1)
System.out.print("\nBenji is not on the list");
else
System.out.printf("\nName: %s had %s points", Names[a], points[a]);
a = findThatName(Names, "Fed");
if (a == -1)
System.out.print("\nFed was not on the list");
else
System.out.printf("\nName: %s had %s points", Names[a], points[a]);
}
public static void showHighest(int[] points, String[] Names) {
int max = points[0];
for (int a = 1; a < points.length; a++) {
if (points[a] > max)
max = points[a];
}
System.out.printf("Highest Name: %s Highest Points: %s", Names[5], max);
}
public static int findThatName(String[] Names, String name) {
int index = -1;
for (int a = 0; a < Names.length; a++) {
if (Names[a].equals(name)) {
index = a;
break;
}
}
return index;
}
}
Specifically, within the showBest method. Instead of using Names[5], am I able to get something like Names[i]? Or maybe how would I use the index of the max score to be the same index of Names?
edit: Sorry I had to change the wording of the code...
You can store both max value and its index.
int index = 0;
int max = scores[0];
for (int i = 1; i < scores.length; i++) {
if (scores[i] > max) {
index = i;
max = scores[i];
}
}
System.out.printf("Max Name: %s Max Score: %s", sNames[index], max);
we should do this in java way, or the Object Oriented way.
For that we will need a Student class.
public class Student implements Comparable<Student> {
private Integer score;
private String name;
public Student() {
super();
}
public Student(Integer score, String name) {
super();
this.score = score;
this.name = name;
}
public Integer getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int compareTo(Student o) {
return this.score.compareTo(o.getScore());
}
#Override
public String toString() {
return "Student [score=" + score + ", name=" + name + "]";
}
}
Then we can use this Student class anywhere and play around with the list of students as we want, like below.
public class Driver {
public static void main(String[] args) {
Student s1 = new Student(67, "Billy");
Student s2 = new Student(86, "Bobbi");
Student s3 = new Student(90, "Barbara");
Student s4 = new Student(20, "Beni");
Student s5 = new Student(55, "Baron");
Student s6 = new Student(98, "Becky");
Student s7 = new Student(90, "Ben");
List<Student> students = new ArrayList<>();
students.add(s1);
students.add(s2);
students.add(s3);
students.add(s4);
students.add(s5);
students.add(s6);
students.add(s7);
System.out.println("Minimum score student is :");
System.out.println(getMinScoreSudent(students));
System.out.println("\nMaximum score student is :");
System.out.println(getMaxScoreSudent(students));
System.out.println("\nAll Sudents :");
printStudentsInConsole(students);
}
public static Student getMinScoreSudent(List<Student> students) {
Collections.sort(students, Comparator.comparing(Student::getScore));
return students.get(0);
}
public static Student getMaxScoreSudent(List<Student> students) {
Collections.sort(students, Comparator.comparing(Student::getScore).reversed());
return students.get(0);
}
public static void printStudentsInConsole(List<Student> students) {
Collections.sort(students, Comparator.comparing(Student::getScore));
students.stream().forEach(student -> System.out.println(student));
}
This prints below message in console.
Minimum score student is :
Student [score=20, name=Beni]
Maximum score student is :
Student [score=98, name=Becky]
All Sudents :
Student [score=20, name=Beni]
Student [score=55, name=Baron]
Student [score=67, name=Billy]
Student [score=86, name=Bobbi]
Student [score=90, name=Barbara]
Student [score=90, name=Ben]
Student [score=98, name=Becky]

How to get a scanner object into a reference variable?

I cannot figure out how to format the code for my if-statements. Typically, I would take a string input from the user and use .equals, however the object I am required to use makes that impossible. Whenever I print the contents of the array, I get references. I want to get a user input stored to be stored in the array and printed in a later line of code.
Question: If possible, how do I get a scanner input to be assigned to a "Team" and referenced for comparison in the if-statements? How should I go about assigning these values?
Here is the code I was given
public class Team implements Comparable<Team> {
public String toString(String team, int wins) {
String winningStatement = team + ": " + wins;
return winningStatement;
}
// Data fields
private String name;
private int winCount;
Team() {
name = "Sooners";
winCount = 1;
}
Team(String inputName) {
name = inputName;
winCount = 1;
}
Team(String inputName, int inputWinCount) {
name = inputName;
winCount = inputWinCount;
}
Here is my attempt at using an ArrayList
Scanner scnr = new Scanner(System.in);
Random rando = new Random();
String name = "hi";
int cycles = 0;
int value = 0;
ArrayList<Team> teams = new ArrayList<Team>();
Team myTeam = new Team();
System.out.println("Welcome to the Advanced Sportsball Tracker!");
while (!name.equals("x")) // looping print statement
{ // x loop begins
System.out.println("Which team just won? (x to exit)");
name = scnr.next();
if (!teams.equals(name))
{
teams.add(thisTeam);
myTeam.setWinCount(1);
}
else if (teams.equals(name))
{
myTeam.incrementWinCount();
}
cycles++;
}// x loop ends
Thank you for the assistance
Judging only by the intent of your example... it appears that this is what you are trying to achieve. As stated though, your question of how ArrayList objects relate to overloaded constructors does not really make sense
public class Team {
// Data fields
private String name;
private int winCount;
public Team() {
name = "Sooners";
winCount = 1;
}
public Team(String inputName) {
name = inputName;
winCount = 1;
}
Team(String inputName, int inputWinCount) {
name = inputName;
winCount = inputWinCount;
}
public String toString(String team, int wins) {
return team + ": " + wins;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWinCount() {
return winCount;
}
public void setWinCount(int winCount) {
this.winCount = winCount;
}
void incrementWinCount() {
winCount++;
}
}
void runSystem() {
List<Team> teams = new ArrayList<>();
Scanner scnr = new Scanner(System.in);
int cycles = 0;
System.out.println("Welcome to the Advanced Sportsball Tracker!");
System.out.println("Which team just won? (x to exit)");
String name = scnr.next();
while (!"x".equals(name)) {
final String teamName = name;
Team team = teams.stream().filter(t -> teamName.equals(t.getName())).findAny().orElse(null);
if (team == null) {
team = new Team(teamName, 1);
teams.add(team);
}
else {
team.incrementWinCount();
}
cycles++;
System.out.println("Which team just won? (x to exit)");
name = scnr.next();
}
}

Comparing lines for a similar String in a text file

I have a text file which looks something like this:
6
3.3 John Rodgers
3.9 Jim Braash
3.5 Kathy Calderon
3.2 Steve Hernandez
2.4 Stacy Lu
2.8 Faith Simmons
I've already written a Student class, which has basic functions:
package com.company;
public class Student {
private String firstName;
private String lastName;
private double grades;
public Student(String firstName, String lastName, double grades) {
this.firstName = firstName;
this.lastName = lastName;
this.grades = grades;
}
#Override
public String toString() {
return lastName + ", " + firstName + ", " + grades;
}
#Override
public boolean equals(Object obj) {
if(obj == null){
return false;
}
Student other = (Student) obj;
if (other.firstName.equals(this.firstName) && other.lastName.equals(this.lastName) && other.grades == this.grades) {
return true;
} else {
return false;
}
}
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
public double getGrade() {
return this.grades;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setGrades(double grades) {
this.grades = grades;
}
}
And this is my Main class:
package com.company;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Student[] s = initialize();
Student max = maxIndex(s);
Student min = minIndex(s);
double avg = avg(s);
flush(max, min, avg);
}
public static void flush(Student max, Student min, double avg) throws FileNotFoundException {
DecimalFormat df = new DecimalFormat("#.#");
double avgFormatted = Double.parseDouble(df.format(avg));
PrintWriter writer = new PrintWriter("final.txt");
writer.write("Highest: " + max);
writer.write("\n");
writer.write("Lowest: " + min);
writer.write("\n");
writer.write("Average GPA: " + avgFormatted);
writer.close();
}
public static Student[] initialize() throws FileNotFoundException {
Scanner reader = new Scanner(new File("data.txt"));
int size = reader.nextInt();
Student[] students = new Student[size];
int index = 0;
while (reader.hasNextLine()) {
double grades = reader.nextDouble();
String firstName = reader.next();
String lastName = reader.next();
Student student = new Student(firstName, lastName, grades);
students[index] = student;
index++;
}
return students;
}
public static double avg(Student[] students) {
double avg = 0;
double sum = 0;
for (int i = 0; i < students.length; i++) {
sum += students[i].getGrade();
avg = sum / students.length;
}
return avg;
}
public static Student maxIndex(Student[] students) {
int max = 0;
for (int i = 1; i < students.length; i++) {
if (students[i].getGrade() > students[max].getGrade()) {
max = i;
}
}
return students[max];
}
public static Student minIndex(Student[] students) {
int min = 0;
for (int i = 1; i < students.length; i++) {
if (students[i].getGrade() < students[min].getGrade()) {
min = i;
}
}
return students[min];
}
}
So, my question involves dealing with the file. Let's say I added the name Jim Braash again into my file without changing the integer at the top. So my file looks like this:
6
3.3 John Rodgers
3.9 Jim Braash
3.9 Jim Braash
3.5 Kathy Calderon
3.2 Steve Hernandez
2.4 Stacy Lu
2.8 Faith Simmons
Even though there are 7 lines, there are still only 6 students because one is repeated. I already implemented the equals() method in my Student class, but I am unable to figure out how I would skip the line in the main() method and still have the same results as before. Thanks.
Use HashSet<Student> instead of Student[] and override hascode to conform to your equals. You won't have any duplicates any more.
Be aware that you can cause serious problems with wrong implementations of equals and hashcode. Properties that are used in this methods shouldn't be modified. This would cause possible duplicates and/or that you may not be able to accesss or remove the modified element in a HashSet.
The other answers have good ideas. But, if you just want a simple way to do it using your equals() method from your Student class, you could try the following for your initialize() method:
public static Student[] initialize() throws FileNotFoundException {
Scanner reader = new Scanner(new File("data.txt"));
int size = reader.nextInt();
Student[] students = new Student[size];
int index = 0;
while (reader.hasNextLine()) {
double grades = reader.nextDouble();
String firstName = reader.next();
String lastName = reader.next();
Student student = new Student(firstName, lastName, grades);
boolean duplicate = false;
for (int i = 0; i < students.length; i++) {
if (student.equals(students[i])) {
duplicate = true;
break;
}
}
if (!duplicate) {
students[index] = student;
index++;
}
}
reader.close(); // <--- Make sure to close the Scanner
return students;
}
Let me know if this works for you.
Instead of array of Student, try use Set of student
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.
This data type have only unique item.
EDIT 1
With array
while (reader.hasNextLine()) {
Double grades = Double.valueOf(reader.next());
String firstName = reader.next();
String lastName = reader.next();
Student student = new Student(firstName, lastName, grades);
if (Arrays.stream(students).noneMatch(s -> student.equals(s))) {
System.out.println(student);
students[index] = student;
index++;
}
}
EDIT 2
You can replace max, min, avg calculation with streams
public static void main(String[] args) throws FileNotFoundException {
Student[] s = initialize();
Student max = Arrays.stream(s).max(Comparator.comparing(student -> student.getGrade())).orElse(null);
Student min = Arrays.stream(s).min(Comparator.comparing(student -> student.getGrade())).orElse(null);
double avg = Arrays.stream(s).map(student -> student.getGrade()).reduce(0d, (x,y) -> x + y).doubleValue() / s.length;
flush(max, min, avg);
}

How to print the first 10 lines from an enhanced for loop

I have a file with over 1000 names it also include the sex and how many people have the name.
example
Sarah F 2000
I am trying to print the first 10 lines that was created from my for loop, but for some reason what i tried is only printing the last line 10 times.
import java.util.*;
import java.io.*;
import java.util.Collections;
public class NameYear
{
private String year;
ArrayList<OneName> oneName = new ArrayList<OneName>();
public NameYear(String year)
{
String line = "";
String Top = "";
Scanner sc = null;
try
{
sc = new Scanner(new File
("/home/mathcs/courses/cs225/koch/names/yob"+year+".txt"));
}
catch (Exception e)
{
System.out.println("Error Year should be between 1880 and 2013 not "+ year);
System.exit(1);
}
while(sc.hasNextLine())
{
// read a line from the input file via sc into line
line = sc.nextLine();
StringTokenizer stk = new StringTokenizer(line, ",");
String name = stk.nextToken();
char sex = stk.nextToken().charAt(0);
int count = Integer.parseInt(stk.nextToken());
OneName list = new OneName(name, sex, count);
oneName.add(list);
}
for (int i = 0 ; i < 10; i++)
{
System.out.println(descending());
}
public String descending()
{
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName)
{
x = b.toString();
}
return x;
OneName file
public class OneName
{
private String Name;
private char Sex;
private int Count;
public OneName(String name, char sex, int count)
{
Name = name;
Sex = sex;
Count = count;
}
public String getName()
{
return Name;
}
public char getSex()
{
return Sex;
}
public int getCount()
{
return Count;
}
public void setName(String name)
{
if (name.length() < 1)
{
throw new NullPointerException("Baby name is missing");
}
Name = name;
}
private char M;
private char F;
public void setSex(char sex)
{
if( sex != M)
{
if(sex != F)
{
throw new IllegalArgumentException("Sex has to be M or F");
}
}
Sex = sex;
}
public void setCount(int count)
{
if(count < 0)
{
throw new IllegalArgumentException("Count cant be negative");
}
Count = count;
}
public String toString()
{
return String.format("%s %c %d", Name, Sex, Count);
}
}
OneNameCount
import java.util.Comparator;
import java.util.Collections;
public class OneNameCountCompare implements Comparator<OneName>
{
public int compare(OneName b1, OneName b2)
{
if(b1.getCount() <b2.getCount())
{
return 1;
}
else
{
return -1;
}
}
}
Main Program
import java.io.*;
import java.util.*;
public class TopNames
{
public static void main(String args[])
{
String line = ""; // string var to hold entire line
if (args.length < 1)
{
System.out.println("\nYou forgot to put a Year on the command line.");
System.exit(1);
};
String inFile = args[0]; // file name off command line
String year = inFile;
NameYear list = new NameYear(year);
}
}
Your descending function returns one string, and always the same string (the last one in the order after sorting the collection). It doesn't matter how often you call it, if the data doesn't change, you'll always get back that same, last, string.
If you want the first 10 after sorting, descending would need to return a List<String> containing those 10:
public List<String> descending()
{
List<String> x = new ArrayList<String>(10);
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName)
{
x.add(b.toString());
if (x.size() == 10) // Or don't use enhanced for, use an index instead
{
break;
}
}
return x;
}
Then when printing it, replace your for (int i = 0 ; i < 10; i++) loop with:
for (String s : descending())
{
System.out.println(s);
}
Your error is here:
for (int i = 0 ; i < 10; i++) {
System.out.println(descending());
}
public String descending() {
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName) {
x = b.toString();
}
return x;
}
First of all in your for loop you are not using the i variable that is your count indicator. This means that the descending() method has no any awareness of i, how he could return something different?
Try to modify descending() in something like this:
public String descending(int i) {
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
OneName b = oneName.get(i);
x = b.toString();
return x;
}

Trying to get the right value answer for my code

Below is the code i have written for a student class and main method. I am having two problems. Firstly, when i try and put main as its own class, if fails to run and compile saying there is an erroneous error with main not being able to reference and create the student classes within main.
Second problem, the last line where it prints out the highest average mark, always prints out 0.0, and i cannot for the life of me work out why.
Can anyone give me the solution to either problems?
I am using NetBeans.
package student;
public class Student {
private String name, id;
private int[] score = new int[3];
public Student()
{
}
public Student(String stName, String stID, int stScore[]) {
this.name = stName;
this.id = stID;
this.score = stScore;
}
public void setName(String nameIn)
{
name = nameIn;
}
public String getName()
{
return name;
}
public double avScore()
{
double total = 0;
int to = 0;
int adder = 0;
for (int i=0; i<score.length; i++)
{
score[i] = adder;
total = total + adder;
}
total = total / score.length;
return total;
}
public void printOut() {
System.out.println("Student Name is: " + name) ;
System.out.println("Student ID is: " + id);
System.out.println("Student scores are: ");
for (int i=0; i<score.length; i++)
{
System.out.println(score[i]);
}
}
public static void main(String args []) {
Student stud1 = new Student("Nico Del Pellegrino", "up660537", new int[] {1, 2, 3});
Student stud2 = new Student("Dylan Scott", "up652312", new int[] {5, 7, 13});
stud1.printOut();
stud2.printOut();
Student stud3 = new Student();
stud3.id = "up645658";
stud3.name = "Alex Barrett";
stud3.score = new int[]{5, 10, 15};
stud3.printOut();
double stud1Score = stud1.avScore();
double stud2Score = stud2.avScore();
double stud3Score = stud3.avScore();
double[] scoreList = {stud1Score, stud2Score, stud3Score};
double highestMark = 0;
for (int i=0; i<scoreList.length;)
{
if(scoreList[i]>highestMark)
{
highestMark = scoreList[i];
i++;
}
else
{
i++;
}
}
System.out.println("The highest average mark is: " + highestMark);
}
}
EDIT:
This is the code in its separate classes, and the error message that occurs when running main.
package student;
public class Student {
private String name, id;
private int[] score = new int[3];
public Student() {
}
public Student(String stName, String stID, int stScore[]) {
this.name = stName;
this.id = stID;
this.score = stScore;
}
public void setName(String nameIn) {
name = nameIn;
}
public String getName() {
return name;
}
public double avScore() {
double total = 0;
int to = 0;
for (int i = 0; i < score.length; i++) {
total = total + score[i];
}
total = total / score.length;
return total;
}
public void printOut() {
System.out.println("Student Name is: " + name);
System.out.println("Student ID is: " + id);
System.out.println("Student scores are: ");
for (int i = 0; i < score.length; i++) {
System.out.println(score[i]);
}
}
}
package Student;
import Student.*;
public class Main {
public static void main(String args []) {
//Create two student objects stud1 and stud2 here
Student stud1 = new Student("Nico Del Pellegrino", "up660537", new int[] {1, 2, 3});
Student stud2 = new Student("Dylan Scott", "up652312", new int[] {5, 7, 13});
//Display information for the two objects
stud1.printOut();
stud2.printOut();
//Create third student object stud3 here
Student stud3 = new Student();
// change object id
stud3.id = "up645658";
// change object name
stud3.name = "Alex Barrett";
// change object exam scores
stud3.score = new int[]{5, 10, 15};
stud3.printOut();
// Find out which student is with the highest average score
int stud1Score = stud1.avScore();
int stud2Score = stud2.avScore();
int stud3Score = stud3.avScore();
//Display his/her details here
}
}
//run:
//Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree //type: Student.Student
// at Student.Main.main(Main.java:9)
//Java Result: 1
//BUILD SUCCESSFUL (total time: 0 seconds)
Your assignment on this line is incorrect:
score[i] = adder;
You initialized adder to 0, so you are effectively placing zeroes throughout your array. No wonder you get 0.0 for the average. Instead of
score[i] = adder;
total = total + adder;
You don't even need adder, just use:
total = total + score[i];

Categories