Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Apr 13th, 2006, 10:46 AM   #1
taporctv
Newbie
 
Join Date: Mar 2006
Posts: 20
Rep Power: 0 taporctv is on a distinguished road
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?
taporctv is offline   Reply With Quote
Old Apr 13th, 2006, 12:09 PM   #2
Toro
Hobbyist Programmer
 
Toro's Avatar
 
Join Date: Apr 2006
Posts: 136
Rep Power: 0 Toro is an unknown quantity at this point
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.
Toro is offline   Reply With Quote
Old Apr 13th, 2006, 1:30 PM   #3
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
Or just use java.util.Collections.sort()
Arevos is offline   Reply With Quote
Old Apr 13th, 2006, 1:37 PM   #4
taporctv
Newbie
 
Join Date: Mar 2006
Posts: 20
Rep Power: 0 taporctv is on a distinguished road
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.
taporctv is offline   Reply With Quote
Old Apr 13th, 2006, 2:53 PM   #5
titaniumdecoy
Expert Programmer
 
titaniumdecoy's Avatar
 
Join Date: Nov 2005
Posts: 843
Rep Power: 3 titaniumdecoy is on a distinguished road
Send a message via AIM to titaniumdecoy
You might find this thread helpful.
titaniumdecoy is offline   Reply With Quote
Old Apr 13th, 2006, 2:58 PM   #6
taporctv
Newbie
 
Join Date: Mar 2006
Posts: 20
Rep Power: 0 taporctv is on a distinguished road
Would it be the smae for an ArrayList?
taporctv is offline   Reply With Quote
Old Apr 13th, 2006, 7:47 PM   #7
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
Quote:
Originally Posted by taporctv
Ok I revised my code. I can't use Collections.sort because I'm sorting Objects.
You can with a custom comparator.
Quote:
Originally Posted by taporctv
I read somewhere else that I should be using the Comparator class. The examples online seem to confusing.
Using the Comparator class is easier than it sounds. You just need to extend and override the compare method. I'll give you an example to show you what I mean:
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
        }
    }
}
The above comparator is created with Java 1.5 in mind, as it uses generics. It should work with any recent Java download. But if you happen to have an old version, remove the generics and use casts instead:
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
        }
    }
}
Then, to use it:
Collections.sort(students, new StudentComparator())
I guess you could also use the Double.compareTo method which should work with Java 1.5's autoboxing:
class StudentComparator extends Comparator<Student>
{
    public int compare(Student a, Student b)
    {
        return a.getExamScore().compareTo(b.getExamScore())
    }
}
Which is small enough to fit in an anonymous class, too...
Collections.sort(students, new Comparator<Student>() {
    public int compare(Student a, Student b) {
        return a.getExamScore().compareTo(b.getExamScore())
    }
});
Arevos is offline   Reply With Quote
Old Apr 15th, 2006, 2:24 AM   #8
pal
Programmer
 
pal's Avatar
 
Join Date: Mar 2005
Location: Washington
Posts: 90
Rep Power: 4 pal is on a distinguished road
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);
			}
		}

	}

}
pal is offline   Reply With Quote
Old Apr 15th, 2006, 7:35 AM   #9
Toro
Hobbyist Programmer
 
Toro's Avatar
 
Join Date: Apr 2006
Posts: 136
Rep Power: 0 Toro is an unknown quantity at this point
hey buddy! Look at the second post, looks familar?! That's the same thing I wrote but with less comments!
Toro is offline   Reply With Quote
Old Apr 15th, 2006, 8:55 AM   #10
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
Quote:
Originally Posted by Toro
hey buddy! Look at the second post, looks familar?! That's the same thing I wrote but with less comments!
Not quite. Your code uses the bubblesort algorithm whilst pal's code also includes methods for quicksort and selection sort.

Personally, I'd use the mergesort included in Java's java.util.Collections class. Much easier
Arevos is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 8:51 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC