![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Mar 2006
Posts: 20
Rep Power: 0
![]() |
Sorting
Basically, I have a input file with an answer key, student id, and the students answers for the exam.
I have figured out how to calculate a students exam score, but now am having trouble sorting by exam scores. Here's my code: [PHP] import java.io.*; import java.lang.String; import java.util.StringTokenizer; import java.lang.Integer; import java.util.ArrayList; /** * Write a description of class FileInput here. * * @author Tim Taporco * @version April 13, 2006 */ public class FileInput { private ArrayList studentScores; // To read in file private String inputFileName = "students.txt"; private FileInputStream fis; private BufferedReader br; // To write to files private String outputFileName = "output.txt"; private FileOutputStream fos; private PrintStream ps; /** * Constructor for objects of class FileInput */ public FileInput() throws Exception { studentScores = new ArrayList(); try{ fis = new FileInputStream(inputFileName); br = new BufferedReader(new InputStreamReader(fis)); fos = new FileOutputStream(outputFileName); ps = new PrintStream(fos); } catch (FileNotFoundException e){ e.printStackTrace(); } } public void readGrades() throws Exception { String answerKey = br.readLine(); String line = br.readLine(); String letter; double score=0; ps.println("Timothy Taporco"); ps.println("Exam Scoring Program"); ps.println(); while(line != null){ StringTokenizer stk = new StringTokenizer(line,"|"); // Assign tokens to strings String studentID = stk.nextToken(); String studentAnswers = stk.nextToken(); score = calculateGrade(answerKey,studentAnswers); letter = calculateLetterGrade(score); ps.println(studentID + " " + score + " " + letter); line = br.readLine(); } } public double calculateGrade(String answerKey,String studentAnswers) { int count = 0; double score = 0; while(count < 20) { if (answerKey.charAt(count) == studentAnswers.charAt(count)){ score += 5; } else{ score += 0; } count++; } return score; } public String calculateLetterGrade(double score) { String letter; if(score >= 93.00){ letter = "A"; } else if (score >= 90.00){ letter = "A-"; } else if (score >= 87.00){ letter = "B+"; } else if (score >= 83.00){ letter = "B"; } else if (score >= 80.00){ letter = "B-"; } else if (score >= 77.00){ letter = "C+"; } else if (score >= 73.00){ letter = "C"; } else if (score >= 70.00){ letter = "C-"; } else if (score >= 67.00){ letter = "D+"; } else if (score >= 63.00){ letter = "D"; } else if (score >= 60.00){ letter = "D-"; } else{ letter = "F"; } return letter; } } [/PHP] The output should look like this: http://courses.cs.vt.edu/~cs1054/S06...cts/scores.txt Im just having trouble sorting the students by grades. Should I assign each students grade info to an arrayList? Or should I create a Student class so I can make student objects? |
|
|
|
|
|
#2 |
|
Hobbyist Programmer
Join Date: Apr 2006
Posts: 136
Rep Power: 0
![]() |
Sort them using an array list. Assign the grades to integer or double array types and do the following.
[PHP] public void sort(int array1[]) { for(int p = 1; p < array1.length; p++) { for (int e = 0 ; e < array1.length - 1;e++) { if(array1[e] > array[e] + 1) swap(array1, e, e+1); } } } public void swap(int array2[], int one, int two) { int hold; hold = array2[one]; array2[one] = array2[two]; array2[two] = hold; } [/PHP] These methods sort the following numbers into ascending order, which is the correct order. The method sort first compares array1[0] to array1[1] and array1[1] to array1[2] and so forth. Then sort them by passing them into another method swap. and if the first array[element] value is great than the next one, it switches their value. I hope this works for you. |
|
|
|
|
|
#3 |
|
Programming Guru
![]() Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5
![]() |
Or just use java.util.Collections.sort()
|
|
|
|
|
|
#4 |
|
Newbie
Join Date: Mar 2006
Posts: 20
Rep Power: 0
![]() |
Ok I revised my code. I can't use Collections.sort because I'm sorting Objects. Everytime a new grade is calculated, Student object is created and added to the arrayList.
[PHP] public void readGrades() throws Exception { String answerKey = br.readLine(); String line = br.readLine(); String letter; double examScore=0; ps.println("Timothy Taporco"); ps.println("Exam Scoring Program"); ps.println(); while(line != null){ StringTokenizer stk = new StringTokenizer(line,"|"); // Assign tokens to strings String studentID = stk.nextToken(); String studentAnswers = stk.nextToken(); examScore = calculateGrade(answerKey,studentAnswers); letter = calculateLetterGrade(examScore); students.add(new Student(studentID,examScore,letter)); line = br.readLine(); } } [/PHP] I read somewhere else that I should be using the Comparator class. The examples online seem to confusing. I need help trying to sort the Student objects by exam Score. |
|
|
|
|
|
#5 |
|
Expert Programmer
|
You might find this thread helpful.
|
|
|
|
|
|
#6 |
|
Newbie
Join Date: Mar 2006
Posts: 20
Rep Power: 0
![]() |
Would it be the smae for an ArrayList?
|
|
|
|
|
|
#7 | ||
|
Programming Guru
![]() Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5
![]() |
Quote:
Quote:
class StudentComparator extends Comparator<Student>
{
public int compare(Student a, Student b)
{
if (a.getExamScore() < b.getExamScore())
{
return -1; // tells Java a is considered less than b
}
else if (a.getExamScore() > b.getExamScore())
{
return 1; // tells Java a is considered greater than b
}
else
{
return 0; // tells Java a is considered equal to b
}
}
}class StudentComparator extends Comparator
{
public int compare(Object a, Object b)
{
if (((Student)a).getExamScore() < ((Student)b).getExamScore())
{
return -1; // tells Java a is considered less than b
}
else if (((Student)a).getExamScore() > ((Student)b).getExamScore())
{
return 1; // tells Java a is considered greater than b
}
else
{
return 0; // tells Java a is considered equal to b
}
}
}Collections.sort(students, new StudentComparator()) class StudentComparator extends Comparator<Student>
{
public int compare(Student a, Student b)
{
return a.getExamScore().compareTo(b.getExamScore())
}
}Collections.sort(students, new Comparator<Student>() {
public int compare(Student a, Student b) {
return a.getExamScore().compareTo(b.getExamScore())
}
}); |
||
|
|
|
|
|
#8 |
|
Programmer
Join Date: Mar 2005
Location: Washington
Posts: 90
Rep Power: 4
![]() |
Here is a list of sort arrays you could use.
I'm in 2nd quarter java in college, and reviewed some sort algorithms recently. public class SortArray
{
public static void main (String[] args)
{
}
/**
The algorithm for a selection sort:
For each array subscript, up to but not including the last,
find the subscript of the smallest value in the subarray starting at
subscript anArray[ fill ] and swap it with the one at subscript
anArray[ fill ].
*/
public static void selectionSort(int[] anArray)
{
int minPos;
int temp;
for( int fill = 0; fill < anArray.length-1; fill++ )
{
minPos = fill;
for( int i = fill; i < anArray.length; i++ )
{
if( anArray[ i ] < anArray[ minPos ] )
minPos = i;
}
temp = anArray[ fill ];
anArray[ fill ] = anArray[ minPos ];
anArray[ minPos ] = temp;
}
}
/**
BubbleSort Algorithm
Beginning at the first element, compare values with the next
higher element. If the 'left' value is higher, swap the values;
compare elements 2 to 3, 3 to 4, etc swapping as necessary
until the largest value is in the last element.
Repeat for the second largest, third largest, n largest...
*/
public static void bubbleSort(int[] anArray)
{
//controls passes through the list
for( int pass = 0; pass < anArray.length-1; pass++ )
{
//controls comparisons of elements
for( int i = 0; i < anArray.length-1-pass; i++ )
{
if( anArray[ i ] > anArray[ i + 1 ] )
{
//swap values
int temp = anArray[ i ];
anArray[ i ] = anArray[ i + 1 ];
anArray[ i + 1 ] = temp;
}
}
}
}
/**
quickSort is a recursive sort; a method that calls itself
with a smaller version of the original problem so that,
eventually, the calls end because the problem is trivial
and now solved (easily).
The algorithm places one value in its correct sorted
location with each call to the quickSort method;
(all values left of it are < and all values right are >;
this is called partitioning) and then performs the same
operation on the left subarray ( 0 -> current position -1),
then on the right subarray (current position +1 -> last);
To partition the array, the algorithm first compares the
first value to the last value, if it is smaller, it compares
the first value to the next to last value, etc until it finds
a 'left' value greater than the 'right' value; if left is > right,
swap; if left[position] == right return the present position
*/
public static void quickSort(int[] arr, int low, int high)
{
// Purpose : Sort values using recursion
// Postcondition: The array values are sorted.
int hi = high;
int lo = low;
if (high > low)
{
// create sub-arrays by placing the first value
// in its correct, sorted position in the array.
int pivot = (high + low)/2;
int mid = arr[pivot];
while (lo <= hi)
{
while (lo < high && arr[lo] < mid)
{
++lo;
}
while (hi > low && arr[hi] > mid)
{
--hi;
}
if (lo <= hi)
{
//swap the values
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
++lo;
--hi;
}
}
if (low < hi)
{
// call QuickSort on the left sub-array.
quickSort(arr, low, hi);
}
if (lo < high)
{
// call QuickSort on the right sub-array.
quickSort(arr, lo, high);
}
}
}
} |
|
|
|
|
|
#9 |
|
Hobbyist Programmer
Join Date: Apr 2006
Posts: 136
Rep Power: 0
![]() |
hey buddy! Look at the second post, looks familar?! That's the same thing I wrote but with less comments!
|
|
|
|
|
|
#10 | |
|
Programming Guru
![]() Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5
![]() |
Quote:
Personally, I'd use the mergesort included in Java's java.util.Collections class. Much easier ![]() |
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|