Returning null in the output - java

The method returns some null skipping some objects.The goal of the method is to return sorterd list of people according to their 'midterm' and 'final' ('midterm' of a person is immediately followed by his 'final') Could smb please help to fix it? Here's the code
public static Exam[] collateExams(Exam[] exams)
{
Exam[] r = new Exam[exams.length];
int index = 0;
for (int i = 0; (i < exams.length) && (index < exams.length/2); i++)
{
if (exams[i].getExamType() == 'm')
{
r[index*2] = new Exam(exams[i].getFirstName(), exams[i].getLastName(), exams[i].getID(), "midterm", exams[i].getScore());
for(int j = 0; (j < exams.length) && (index < exams.length/2); j++)
{
if((exams[j].getExamType() == 'f') && (exams[i].getID() == exams[j].getID()))
{
r[index*2 + 1] = new Exam(exams[i].getFirstName(), exams[i].getLastName(), exams[i].getID(), "final", exams[i].getScore());
}
}
}
index++;
}
return r;
here's the output:
null
null
Bill Gates 6 midterm 90
Bill Gates 6 final 90
James Gosling 3 midterm 100
James Gosling 3 final 100
Sergey Brin 22 midterm 98
null
Dennis Ritchie 5 midterm 94
Dennis Ritchie 5 final 94
Steve Jobs 9 midterm 95
Steve Jobs 9 final 95
Here's the unsorted list which is passed as a parameter:
Steve Jobs 9 final 91
Bill Gates 6 midterm 90
James Gosling 3 midterm 100
Sergey Brin 22 midterm 98
Dennis Ritchie 5 midterm 94
Steve Jobs 9 midterm 95
Dennis Ritchie 5 final 100
Jeff Dean 7 midterm 100
Bill Gates 6 final 96
Jeff Dean 7 final 100
Sergey Brin 27 final 97
James Gosling 3 final 100

Either your entire class is posting the same question, or you are Joshua mark II. Now, other variations said only one for loop and other restrictions, so I am going to ignore all of that and address the messed up double loop above. This will fix the loop above:
public static Exam[] collateExams(Exam[] exams)
{
Exam[] r = new Exam[exams.length];
int index = 0;
for (int i = 0; i < exams.length ; i++)
{
if (exams[i].getExamType() == 'm')
{
r[index*2] = new Exam(exams[i].getFirstName(), exams[i].getLastName(), exams[i].getID(), 'm', exams[i].getScore());
for(int j = 0; j < exams.length; j++)
{
if((exams[j].getExamType() == 'f') && (exams[i].getID() == exams[j].getID()))
{
r[index*2 + 1] = new Exam(exams[j].getFirstName(), exams[j].getLastName(), exams[j].getID(), 'f', exams[j].getScore());
}
}
index++;
}
}
return r;
}
Output:
Sorted list:
Exam [fn=Bill, ln=Gates, id=6, ex=m, score=90]
Exam [fn=Bill, ln=Gates, id=6, ex=f, score=96]
Exam [fn=James, ln=Gosling, id=3, ex=m, score=100]
Exam [fn=James, ln=Gosling, id=3, ex=f, score=100]
Exam [fn=Dennis, ln=Ritchie, id=5, ex=m, score=94]
Exam [fn=Dennis, ln=Ritchie, id=5, ex=f, score=100]
Exam [fn=Steve, ln=Jobs, id=9, ex=m, score=95]
Exam [fn=Steve, ln=Jobs, id=9, ex=f, score=91]
Exam [fn=Jeff, ln=Dean, id=7, ex=m, score=100]
Exam [fn=Jeff, ln=Dean, id=7, ex=f, score=100]
Exam [fn=Sergey, ln=Brin, id=22, ex=m, score=99]
Exam [fn=Sergey, ln=Brin, id=22, ex=f, score=97]

These items which show null are never initialized thats why..
public class Example2 {
String array[] = new String[15];
public Example2(){
for(int j=0; j<array.length-1; j++)
array[j]="j";
for(int j=0; j<array.length; j++)
System.out.println(array[j]);
}
public static void main(String[] args){
new Example2();
}
}
This example will print 14 ("J") and one null.Why? cause array[15] is not initialized.
So on your example with i am sure that these items show null cause are never initialized.

[EDITED] #Michael, your code is giving me this output with only one null:
Sorted list:
Bill Gates 6 midterm 90
Bill Gates 6 final 96
James Gosling 3 midterm 100
James Gosling 3 final 100
Sergey Brin 22 midterm 98
null
Dennis Ritchie 5 midterm 94
Dennis Ritchie 5 final 100
Steve Jobs 9 midterm 95
Steve Jobs 9 final 91
Jeff Dean 7 midterm 100
Jeff Dean 7 final 100
Here's the Exam class which has toString method:
class Exam {
private String firstName;
private String lastName;
private int ID;
private String examType;
private int score;
public Exam(String firstName, String lastName, int ID, String examType, int score)
{
this.firstName = firstName;
this.lastName = lastName;
this.ID = ID;
this.examType = examType;
this.score = score;
}
public String getFirstName()
{
return this.firstName;
}
public String getLastName()
{
return this.lastName;
}
public int getID()
{
return this.ID;
}
public char getExamType()
{
char examTypeCasted = 0;
examTypeCasted = examType.charAt(0);
return Character.toUpperCase(examTypeCasted);
}
public int getScore()
{
return this.score;
}
public String toString()
{
return this.firstName + " " + this.lastName + " " + this.ID + " " + this.examType + " " + this.score;
}
public boolean equals(Exam e)
{
if(this.equals(e))
return true;
else
return false;
}
}

Related

Using multiple arrays as information in a method

I'm struggeling a bit with arrays and user what's inside with loops. I have this question for example (ignore what's inside of the previewOrder method, i was trying stuff out):
public class Ex1_19 {
final static String NAMES[]= {"Spa reine 25 ","Bru plate 50","Bru pét 50",
"Pepsi","Spa orange", "Schweppes Tonic","Schweppes Agr","Ice Tea","Ice Tea Pêche",
"Jus d'orange Looza", "Cécémel", "Red Bull","Petit Expresso","Grand Expresso","Café décaféiné ",
"Lait Russe ","Thé et infusions","Irish Coffee ","French Coffee ","Cappuccino","Cécémel chaud",
"Passione Italiano","Amour Intense", "Rhumba Caliente ","Irish Kisses ","Cuvée Trolls 25",
"Cuvee Trolls 50","Ambrasse-Temps 25","Ambrasse-Temps 50 ","Brasse-Temps Cerises 25",
"Brasse-Temps Cerises 50","La Blanche Ste Waudru 25","Blanche Ste Waudru 50",
"Brasse-Temps citr 25","Brasse-Temps citr 50","Spaghetti Bolo ","Tagl Carbonara",
"Penne poulet baslc ","Tagl American","Tagl saum"};
final static double NETPRICES[]= {2.2, 2.3,3.9,2.2,2.2,2.6,2.6,2.6,2.6,2.6,2.6,4.5,2.2,2.2,2.2,2.5,2.5,7.0,7.0,2.8,2.8,6.2,6.2,6.2,6.2,
2.9,5.5,2.7,5.1,3.1,5.8,2.6,4.9,2.6,4.9,10.8,11.2,12.2,14.5,16.9};
public static void main(String[] args) {
int Order[][]={{3,2},{1,3},{12,4},{37,1},{36,3},{0,0},{0,0},{0,0}, {0,0}};
previewOrder(Order);
}
public static void previewOrder(int order[][]) {
int i = 0;
int j = 0;
while(i < order.length && j < order.length) {
System.out.println(NAMES[i]);
i++;
j++;
}
}
}
My result has to be something like this but with what's inside the "order" array:
Bru pét 50 3.9 2 7,80
Spa reine 25 2.2 3 6,60
Red Bull 4.5 4 18,00
Tagl Carbonara 11.2 1 11,20
Spaghetti Bolo 10.8 3 32,40
In my exercice I have to use a while loop and I have to put the order array in my method parameters. I can't figure out how to make them all communicate.
Sorry if this question has been answered somewhere else but I don't know how to search for it.
EDIT: I know that Orders does not use zero based index, but starts at 1. This is probably because "Order" is supposed to be a user entry. The first number of the array is like a drink number.
I wasn't very clear on the expected output.
Bru pét 50 (NAME[3]) 3.9 (NETPRICE[3]) 2 (Order[][2]) 7.80 NETPRICE[3] * Order[][2] and this for every occurence in Order
The Order array (btw: should be named order or orders) obviously contains references to ordered items and their amount. It's a two dimensional array, like a table with two columns.
Your expected output of "Bru pét 50 3.9 2 7,80", coming from Order[0] {3,2} indicates that the first element (Order[0][0]) is a reference to the items name (from NAMES) and the price (from NETPRICES). The second value of each "row" is the item amount (2) and finally there's the computed total.
For reasons unknown, Orders does not not use zero-based indexed, but starts at 1. So ORDER[0] having value {3,2} actually referes to NAMES[2] and NETPRICES[2]. This needs to be taken into account when picking the right item form NAMES and NETPRICES.
Anyhow: This is what your method could look like. You still need to tweak the output according to your needs.
public static void previewOrder(int order[][]) {
for (int i = 0; i < order.length; i++) {
int index = order[i][0] - 1;
if (index < 0 || index > NAMES.length || index > NETPRICES.length) {
continue;
}
String name = NAMES[order[i][0] - 1];
double price = NETPRICES[order[i][0] - 1];
int amount = order[i][1];
double total = amount * price;
System.out.println(
name + " " + price + " " + amount + " " + total
);
}
}
Try this.
public static void previewOrder(int order[][]) {
Stream.of(order)
.filter(x -> x[0] != 0)
.forEach(x -> {
String name = NAMES[x[0] - 1];
int unit = x[1];
double price = NETPRICES[x[0] - 1];
System.out.printf("%s %.1f %d %.2f%n",
name, price, unit, price * unit);
});
}
output:
Bru p?t 50 3.9 2 7.80
Spa reine 25 2.2 3 6.60
Red Bull 4.5 4 18.00
Tagl Carbonara 11.2 1 11.20
Spaghetti Bolo 10.8 3 32.40
or
public static void previewOrder(int order[][]) {
for (int[] row : order) {
if (row[0] == 0)
continue;
String name = NAMES[row[0] - 1];
int unit = row[1];
double price = NETPRICES[row[0] - 1];
System.out.printf("%s %.1f %d %.2f%n",
name, price, unit, price * unit);
}
}
When I see tightly coupled arrays, I think of creating a class.
public class Product {
String name;
double unitPrice;
public Product () {
name = "*** Unnamed Product ***";
unitPrice = 0.0;
}
public Product (String name, double unitPrice) {
this.name = name;
this.unitPrice = unitPrice;
}
public String getName () { return name; }
public double getPrice () { return unitPrice; }
public String toString () { return name + " # " + unitPrice + " ea.";}
}
Then, you can have one array where you previously had two:
public class Ex1_19 {
static final Product [] productList = {
new Product("Spa reine 25 ", 2.2),
new Product("Bru plate 50", 2.3),
new Product("Bru pét 50", 3.9),
new Product("Pepsi", 2.2),
new Product("Spa orange", 2.2),
new Product("Schweppes Tonic", 2.6),
new Product("Schweppes Agr", 2.6),
new Product("Ice Tea", 2.6)
// and so on
};
}
The preview order method, without formatted output, might look like this:
public static void previewOrder (int[][] order) {
double total = 0.0;
double itemCount = 0;
int lineNum = 0;
for (int i = 0; i < order.length; ++i) {
int row = order[i][0] - 1;
if (row < 0) {
break;
}
int qty = order [i][1];
double amt = productList [row].getPrice () * qty;
System.out.println (++lineNum + " " + productList[row].getName()
+ " " + productList[row].getPrice () + " " + qty
+ " " + amt);
itemCount += qty;
total += amt;
}
System.out.println ("===\nTotal: " + total + " for " + itemCount + " items.");
}

Basic Java programming with Multiple ArrayLists

In the following code, I have taken in a list of 5 student names, and loading them in an ArrayList of type String.
import java.util.Scanner;
import java.util.ArrayList;
public class QuizAverage
{
public static void main( String[] args ) {
final int NAMELIMIT = 5 ;
final int QUIZLIMIT = 5 ;
ArrayList<String> sNames = new ArrayList<String>();
ArrayList<String> sFamily = new ArrayList<String>();
Scanner in = new Scanner(System.in);
//Load the 5 names of the students in the arraylist
for(int i = 1; i<=NAMELIMIT; i++)
{
String[] input = in.nextLine().split("\\s+");
sNames.add(input[0]);
sFamily.add(input[1]);
}
System.out.println("Name: ");
System.out.println();
for(int i=0; i<NAMELIMIT; i++)
{
System.out.println("Name: " +sNames.get(i) + " " + sFamily.get(i));
}
System.out.println();
}
}
However, now I am trying to add to the code a part that reads in marks for 5 quizes for each student and loads the quiz marks in An ArrayList of type Integer
So I know I need to use
ArrayList<Integer> quizMarks = readArrayList(readQuiz.nextLine());
and then pass it on to this code which takes the quiz marks and weights them out of 15 instead of 100
public static ArrayList<Integer> readArrayList(String input)
{
ArrayList<Integer> quiz = new ArrayList<Integer>();
int i = 1;
while (i <= QUIZLIMIT)
{
if (readQuiz.hasNextInt()) {
quiz.add(readQuiz.nextInt());
i++;
} else {
readQuiz.next(); // toss the next read token
}
}
return quiz;
}
//Computer the average of quiz marks
public static void computerAverage(ArrayList<Integer>quiz)
{
double total = 0 ;
for(Integer value : quiz)
{
total = total + value;
}
total *= MAX_SCORE/100;
System.out.println("Quiz Avg: "+ total / QUIZLIMIT );
}
}
So my current code with the input:
Sally Mae 90 80 45 60 75
Charlotte Tea 60 75 80 90 70
Oliver Cats 55 65 76 90 80
Milo Peet 90 95 85 75 80
Gavin Brown 45 65 75 55 80
Gives the output
Name: Sally Mae
Name: Charlotte Tea
Name: Oliver Cats
Name: Milo Peet
Name: Gavin Brown
when the desired output is
Name: Sally Mae Quiz Avg: 10.5
Name: Charlotte Tea Quiz Avg: 11.25
Name: Oliver Cats Quiz Avg: 10.95
Name: Milo Peet Quiz Avg: 12.75
Name: Gavin Brown Quiz Avg: 9.6
As Jim said, you should store the marks and the name of the student in the same class. The reason for doing that is say going forward you want to find the marks of a particular student named Raj.
In your implementation you would have to go through the first array for find the index of the person named Raj and then go to the same index in the marks array. If there was no problem in initializing the first array but there was some problem in creating the marks array you might end up with the wrong marks.
Also if you have to add a new attribute to a student you would have to create a new array and then add one more logic to read that data.
Having a class gives you an easy way to group all the data belonging to a student.
For your problem of averaging, I'd have a class as follows
class Student {
private String name;
private Double marks;
public Student(String name, String marks) {
this.name = name;
this.marks = marks;
}
//getters setters
}
Have a list of Student
List<Student> students = new ArrayList<Student>();
After reading you will append the object to this list
students.add(new Student(name, marks));
Computing average is as follows
Double average = 0;
for(Student student: students) {
average += student.getMarks();
}
average = average / student.size();
Checkout https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html for other ways to get the average.
Don't use parallel arrays. Use a Student class instead:
public class Student {
private String name;
private String family;
private List<Integer> marks = new ArrayList<>();
public Student(String name, String family)
{
this.name = name;
this.family = family;
}
// getters, setters
...
public void addMark(int mark)
{
this.marks.add(mark);
}
public void getAverage()
{
... // etc
}
}
Then store instances of this class in a single list in your main program
List<Student> students = new ArrayList<>();
You haven't called computerAverage() yet from what I see.

Printing Out Object In Java

I have a file that has the following content:
5
Derrick Rose
1 15 19 26 33 46
Kobe Bryant
17 19 33 34 46 47
Pau Gasol
1 4 9 16 25 36
Kevin Durant
17 19 34 46 47 48
LeBron James
5 10 17 19 34 47
I'm trying to put the names and then numbers for the ticket in an array in my ticket constructor, however when I instantiate my ticket object and try to display it I get the following:
Tickets: lottery$Ticket#33909752
Tickets: lottery$Ticket#55f96302
Tickets: lottery$Ticket#3d4eac69
Tickets: lottery$Ticket#42a57993
Tickets: lottery$Ticket#75b84c92
Does the problem in my constructor for ticket or is it impossible to print an array without making it a string first?
int lim = scan.nextInt();
scan.nextLine();
for(int i = 0; i < lim; i++)
{
String name = scan.nextLine();
String num = scan.nextLine();
String[] t = num.split(" ");
int[] tichold = new int[t.length];
for(int j = 0; j < t.length; j++)
{
tichold[j] = Integer.parseInt(t[j]);
}
Ticket ticket = new Ticket(name, tichold);
System.out.println("Ticket: " + ticket);
}
scan.close();
}
public static class Ticket
{
public String name;
public int[] tarray;
public Ticket(String name, int[] tarray)
{
this.name = name;
this.tarray = tarray;
}
}
You need to provide toString method for it. Here is sample, which you can use:
#Override
public String toString() {
return "Ticket{" +
"name='" + name + '\'' +
", tarray=" + Arrays.toString(tarray) +
'}';
}
In order to accomplish that you need to write an overiding toString method and write in there want you want.
public String toString(){
return //whatever you need goes here and will be printed when you try and
//print the object
}
You must override the toString method which is inherited from the Object class:
#Override
public String toString(){
return //Enter the format you require
}
Remember ticket is a reference variable so when you print it out, you will get the hashcode along with the name of the class of which the object is an instance.

What am I doing here wrong?

The initial output of the texfile is this. NO ARRAYLIST OR COMPARATOR IS ALLOWED:
Steve Jobs 9 f 91
Bill Gates 6 m 90
James Gosling 3 m 100
James Gosling 3 f 100
Dennis Ritchie 5 m 94
Steve Jobs 9 m 95
Dennis Ritchie 5 f 100
Jeff Dean 7 m 100
Bill Gates 6 f 96
Jeff Dean 7 f 100
Sergey Brin 27 f 97
Sergey Brin 22 m 98
The collateExams method collates/sorts exam objects starting with the first 'm' (midterm) of the first object and immediately followed by the same person's 'f'(final). Only a SINGLE loop construct is allowed. The output from collateExams() should be the one below but my code is not working, i.e. collateExams method is not working. Could smb help me with that? The output from collateExams() should be
Bill Gates 6 m 90
Bill Gates 6 f 96
James Gosling 3 m 100
James Gosling 3 f 100
Dennis Ritchie 5 m 94
Dennis Ritchie 5 f 100
Steve Jobs 9 m 95
Steve Jobs 9 f 91
Jeff Dean 7 m 100
Jeff Dean 7 f 100
Sergey Brin 22 m 98
Sergey Brin 27 f 97
Im getting NullExceptions at
r[2*position[exams[i].getID()]+1] = new Exam(r[i].getFirstName(), r[i].getLastName(), r[i].getID(), r[i].getExamType(), r[i].getScore());
import java.io.*;
import java.util.*;
class P2 {
public static void main(String [] args) throws FileNotFoundException
{
Scanner data = new Scanner(new File("Exam.txt"));
Exam[] readObjects = readAllExams(data);
Exam[] collateObjects = collateExams(readObjects);
System.out.println("1) Initially the list of exams of students is: ");
System.out.println();
for(int i = 0; i < readObjects.length; i++)
{
System.out.println(readObjects[i]);
}
System.out.println();
System.out.println("Sorted list: ");
for (int i = 0; i < collateObjects.length; i++)
{
System.out.println(collateObjects[i]);
}
}
public static Exam[] readAllExams(Scanner s) throws ArrayIndexOutOfBoundsException
{
String firstName = "";
String lastName = "";
int ID = 0;
String examType = "";
char examTypeCasted;
int score = 0;
int index = 0;
Exam[] object = new Exam[s.nextInt()];
while(s.hasNext())
{
//Returns firtsName and lastName
firstName = s.next();
lastName = s.next();
//Returns ID number
if(s.hasNextInt())
{
ID = s.nextInt();
}
else
s.next();
//Returns examType which is 'M' or 'F'
examType = s.next();
examTypeCasted = examType.charAt(0);
if(s.hasNextInt())
{
score = s.nextInt();
}
//Exam[] object = new Exam[s.nextInt()];
object[index] = new Exam(firstName, lastName, ID, examTypeCasted, score);
//System.out.println();
index++;
}
readExam(s);
return object;
}
public static Exam readExam(Scanner s)
{
String firstName = "";
String lastName = "";
int ID = 0;
String examType = "";
char examTypeCasted = 0;
int score = 0;
while (s.hasNext())
{
//Returns firtsName and lastName
firstName = s.next();
lastName = s.next();
//Returns ID number
if(s.hasNextInt())
{
ID = s.nextInt();
}
//Returns examType which is 'M' or 'F'
examType = s.next();
examTypeCasted = examType.charAt(0);
if(s.hasNextInt())
{
score = s.nextInt();
}
}
Exam temp = new Exam(firstName, lastName, ID, examTypeCasted, score);
return temp;
}
public static Exam[] collateExams(Exam[] exams)
{
Exam[] r = new Exam[exams.length];
int [] position = new int[exams.length];
int index = 0;
for (int i = 0; (i < exams.length) && (i < position.length); i++)
{
position[i] = -1;
if(exams[i].getExamType()=='m')
{
if(position[exams[i].getID()]==-1)
{
r[index*2] = new Exam(r[i].getFirstName(), r[i].getLastName(), r[i].getID(), r[i].getExamType(), r[i].getScore());
position[exams[i].getID()] = 2*index;
}
else
r[2*position[exams[i].getID()] - 1] = new Exam(r[i].getFirstName(), r[i].getLastName(), r[i].getID(), r[i].getExamType(), r[i].getScore());
}
else
{
if(position[exams[i].getID()]==-1)
{
r[index*2+1] = new Exam(r[i].getFirstName(), r[i].getLastName(), r[i].getID(), r[i].getExamType(), r[i].getScore());
position[exams[i].getID()] = 2*index+1;
}
else
r[2*position[exams[i].getID()]+1] = new Exam(r[i].getFirstName(), r[i].getLastName(), r[i].getID(), r[i].getExamType(), r[i].getScore());
}
index++;
}
return r;
}
}
This is absolute and complete kluge, but it meets your criteria. If this doesn't work for you then you would have to look at object creation or something else to fit your needs.
static int maxId = 0;
public static void main(String [] args) throws FileNotFoundException
{
Scanner data = new Scanner(Answer28522397.class.getClassLoader().getResourceAsStream("exams.txt"));
Exam[] readObjects = readAllExams(data);
System.out.println("1) Initially the list of exams of students is: ");
System.out.println();
for(int i = 0; i < readObjects.length; i++)
{
System.out.println(readObjects[i]);
}
Object[][] collatedObjects = collateExams(readObjects);
System.out.println("");
System.out.println("Sorted list: ");
for (int i = 0; i < collatedObjects.length; i++)
{
if (collatedObjects[i][0] != null && collatedObjects[i][1] != null)
{
System.out.println(collatedObjects[i][0]);
System.out.println(collatedObjects[i][1]);
}
}
}
public static Exam[] readAllExams(Scanner s) throws ArrayIndexOutOfBoundsException
{
int index = 0;
Exam[] object = new Exam[s.nextInt()];
while(s.hasNext())
{
Exam e = readExam(s);
maxId = e.getID() > maxId ? e.getID() : maxId;
object[index] = e;
index++;
}
return object;
}
public static Exam readExam(Scanner s)
{
String firstName = "";
String lastName = "";
int ID = 0;
String examType = "";
char examTypeCasted = 0;
int score = 0;
//Returns firtsName and lastName
firstName = s.next();
lastName = s.next();
//Returns ID number
if(s.hasNextInt())
{
ID = s.nextInt();
}
//Returns examType which is 'M' or 'F'
examType = s.next();
examTypeCasted = examType.charAt(0);
if(s.hasNextInt())
{
score = s.nextInt();
}
return new Exam(firstName, lastName, ID, examTypeCasted, score);
}
public static Object[][] collateExams(Exam[] exams)
{
Exam [] r = new Exam[exams.length];
System.arraycopy(exams, 0, r, 0, exams.length);
Object[][] collation = new Object[maxId+1][2];
for(Exam exam : exams)
{
if (exam.getExamType() == 'm')
{
collation[exam.getID()][0] = exam;
}
else
{
collation[exam.getID()][1] = exam;
}
}
return collation;
}

Calling a list as an array from a .txt and need to display an average

The .txt file looks like this:
Gator Ali 85
Vator Ella 75
Beam James 95
Lastin Class 55
I've seen other people trying to get similar code on here, but none of that helped.
I can get the average; however, I also need to print out if the score 10 points below average.
Here is my output:
run:
Welcome to the Student Scores Application.
Ali Gator 85
Ella Vator 75
James Beam 95
Class Lastin 55
Beam, James: 95
Gator, Ali: 85
Lastin, Class: 55
Vator, Ella: 75
Your score is 10 points or more below the class average
Class Average: 77.5
Here is my code:
public static void main(String[] args) throws Exception {
Scanner aScanner = new Scanner(new FileReader("src//chapt11//Studentdata.txt"));
System.out.println("Welcome to the Student Scores Application.\n");
int nStudent = 100;
Student[] studentArray = new Student[nStudent];
int counter = 0;
while (aScanner.hasNext()) {
String lastName = aScanner.next();
String firstName = aScanner.next();
int score = aScanner.nextInt();
System.out.println(firstName + " " + lastName + " " + score);
studentArray[counter++] = new Student(lastName, firstName, score);
Arrays.sort(studentArray, 0, counter);
}
System.out.println();
for(int j = 0; j < counter; j++){
System.out.println(studentArray[j]);
}
double sum = 0;
for(int j = 0; j < counter; j++){
sum += studentArray[j].getExamScore();
}
double average = (sum*1.0)/counter;
for(int j = 0; j < counter; j++){
int score = studentArray[j].getExamScore();
if (score <= (average - 10)){
System.out.println("Your score is 10 points or more below the class average");
}
}
System.out.println();
System.out.println("Class Average: " + average);
System.out.println();
aScanner.close();
}
class Student implements Comparable<Student> {
private String firstName;
private String lastName;
private int score;
public Student(String firstName, String lastName, int score) {
this.firstName = firstName;
this.lastName = lastName;
this.score = score;
}
public int getExamScore() {
return score;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
#Override
public int compareTo(Student s) {
if(!firstName.equalsIgnoreCase( s.firstName)) {
return firstName.compareToIgnoreCase(s.firstName);
}
if(!lastName.equalsIgnoreCase(s.lastName)) {
return lastName.compareToIgnoreCase(s.lastName);
}
return score - s.score;
}
#Override
public String toString(){
return firstName + ", " + lastName + ": "+ score;
}
}
I see some problems with your code.
Firstly, there is no need to call Arrays.sort every time you add a Student to the studentArray. Place this method call outside the end of while which sorts complete array with just one call to the method.
Secondly, and more importantly, how do you want the Student objects compared?
The compareTo method inside Student doesn't make sense. If you want the students to be sorted only by their scores you should have something like this:
#Override
public int compareTo(Student s) {
return this.score - s.score;
}
And as far as the expected output is concerned, this is what's happening.
The following line prints each Student as they are added to the array:
System.out.println(firstName + " " + lastName + " " + score);
This part prints each Student object again:
for (int j = 0; j < counter; j++) {
System.out.println(studentArray[j]);
}
And this line gets printed only when score <= (average - 10) evaluates to true:
System.out.println("Your score is 10 points or more below the class average");
I believe now you see the problem.

Categories

Resources