Results 1 to 19 of 19
- 05-01-2011, 10:19 PM #1
Member
- Join Date
- May 2011
- Posts
- 10
- Rep Power
- 0
Student Name Bubble Sort, Read And Write From Text Files
Hi all, I am new to the forums so I hope I am posting in the right spot. Here is my problem, I have a program due for school Tuesday and i have gotten pretty far but I am getting some errors and I have been jerking around for hours trying to get it fixed. Here is what the program needs to do, the readandsortdata program reads a file from disk with a list of student first and last names, it then is suppose to sort the names and put them in alphabetical order via bubblesort and then write them to disk in a different file. I cant figure it out, I will display the code below, any help would be greatly appreciated, thanks
The Student.java code ------>
public class Student
{
protected String lastName;
protected String firstName;
Student()
{
lastName =new String("unknown");
firstName =new String("unknown");
} //end of constructor
Student(String f, String l)
{
this.lastName = l;
this.lastName = f;
}//end of overloaded constructor
public boolean equals(Student o)
{
return this.firstName.equals(o.firstName) && this.lastName.equals(o.lastName);
}//end of equals
public int compareTo(Student n)
{
int lastCmp = this.lastName.compareTo(n.lastName);
return (lastCmp == 0 ? firstName.compareTo(n.firstName) : lastCmp);
}//end of compareTo
public String toString()
{
return ("Firstname-> "+firstName+" LastName-> "+lastName);
}//end of toString method
}// end of Student
ReadAndSortData.java Program --------->
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class ReadDataAndSort
{
public static void main(String [] args)
{
System.out.println("Welcome to name sorter");
String first = new String();
String last = new String();
//create ArrayList object or Integers
ArrayList<Student> arrList = new ArrayList<Student>();
int count = 0;
java.io.File sourceFile = new java.io.File("students.txt");
String temp = new String();
try
{
Scanner input = new Scanner(sourceFile);
while (input.hasNext())
{
first = input.next();
last = input.next();
System.out.print("DEBUG statement first-> "+first); //used for debugging
System.out.println(" last -> "+last+" \t$$"); //used for debugging
Student oneStudent = new Student(last,first);
arrList.add(oneStudent);
}//end of while loop to read all the data from the disk
for (Student E : arrList)
System.out.println(E); //verify all the input data was read in from disk
input.close();//done reading all the names from disk
}//end of try block
catch (FileNotFoundException xx)
{
System.out.println("Error ---> Data file does not exist");
}
catch (NumberFormatException xxx)
{
System.out.println("Error ---> Can NOT parse string data to an integer");
System.out.println("String data is in temp->"+temp);
}
catch (Exception error)
{
System.out.println("some RUN-TIME error has occured");
System.out.println("Error ---> "+error);
}//end of catch
Iterator<Student> it = arrList.iterator();
System.out.println("-------------------------------------");
Student [] unsortedArray = new Student[arrList.size()];
while (it.hasNext()) //create a loop move an arrayList into an array
{
Student anObj = it.next();//get Object out of ArrayList
unsortedArray[count] = anObj; // work on this line of code......;
count = count + 1;
System.out.println(anObj);//only used for testing
}//end of while loop to empty arrayList named arrList
for (int i = 0 ; i< unsortedArray.length; ++i)
System.out.println(unsortedArray[i]);//debug
bubbleSort(unsortedArray, unsortedArray.length);
/* public void writeFileToDisk(int x)
{
file = ("students2.txt");
try
{
File outFile = new File(file);
PrintWriter output = new PrintWriter(outFile);
output.println(E + " ");
output.close();
}
catch (Exception error)
{
}//End Of Error Catching
}//End Of Write */
}//end of main method
private static void bubbleSort (unsortedArray,int length)
{
int temp;
int counter;
int index;
for (counter = 0; counter<length - 1; counter ++)
{
for(index = 0; index<length - 1 - counter; index ++)
{
if(unsortedArray[index] .compareTo(unsortedArray[index + 1]) > 0)
{
temp = unsortedArray[index];
unsortedArray[index] = unsortedArray[index + 1];
unsortedArray[index + 1] = temp;
}//End Of If Loop For Swap
}//End Of Inner Loop
}//End Of Outer Loop
}
}//end of class
Any help would be greatly appreciated, my brain is hurting, a lot. Thanks in advance
- 05-01-2011, 10:20 PM #2
Member
- Join Date
- May 2011
- Posts
- 10
- Rep Power
- 0
PS the Student code compiles fine, it is the other one that does not. Thanks
- 05-01-2011, 10:22 PM #3
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
please wrap your code in code tags
Also, please ask specific questions. What problems are you running into? If you get errors please copy/paste them here.Java Code:[[i][/i]code] YOUR CODE HERE [[i][/i]/code]
- 05-01-2011, 11:58 PM #4
Member
- Join Date
- May 2011
- Posts
- 10
- Rep Power
- 0
sorry, I will use the code tags next time. I am getting this error in the tool output from text pad
G:\JAVA\classes\ReadDataAndSort.java:113: incompatible types
found : Student
required: int
temp = unsortedArray[index];
^
G:\JAVA\classes\ReadDataAndSort.java:115: incompatible types
found : int
required: Student
unsortedArray[index + 1] = temp;
^
2 errors
Tool completed with exit code 1
Thanks again, sorry for the new guy crap too.
- 05-02-2011, 12:33 AM #5
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
As the errors suggest, you are trying to store a string in an array of students.
- 05-02-2011, 12:42 AM #6
Member
- Join Date
- May 2011
- Posts
- 10
- Rep Power
- 0
can you give me any direction? this is the first time we have worked with this kind of thing. At this point in the program I am just attempting to call the sort method and then do the sort method. Any code help please, i am totally burned out, I am not just some kid trying to get my homework done, i am a 32 year old who is just beating my head trying to figure this out. Ha, thanks
- 05-02-2011, 12:50 AM #7
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
As far as the exact logic of HOW to sort with bubble sort, I may not be the best help. However, the errors you are getting are mismatch errors
In this bit of code, the prototype is off, you have one formal parameter, and one actual parameter. A method head should only contain formal parameters. It should instead look something like thisJava Code:private static void bubbleSort (unsortedArray,int length) { int temp; int counter; int index; for (counter = 0; counter<length - 1; counter ++) { for(index = 0; index<length - 1 - counter; index ++) { if(unsortedArray[index] .compareTo(unsortedArray[index + 1]) > 0) { temp = unsortedArray[index]; unsortedArray[index] = unsortedArray[index + 1]; unsortedArray[index + 1] = temp; }//End Of If Loop For Swap }//End Of Inner Loop }//End Of Outer Loop } }
To drive home this point even more, if you are passing an array you can access the length of the array with arrayName.length, so you can change the header to thisJava Code:private static void bubbleSort (Student[] unsortedArray,int length)
Then in the loop you can use the condition like thisJava Code:private static void bubbleSort(Student[] unsortedArray)
The next problem is that temp is an integer, but you try storing the item at location i, which is a student. You can't store a student in an item with an int reference. Try making temp look like thisJava Code:for(int i = 0; i < unsortedArray.length; ++i)
Then store the student in the temp variable.Java Code:Student temp;
Last edited by sunde887; 05-02-2011 at 12:53 AM.
- 05-02-2011, 12:59 AM #8
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
How you are handling the exceptions is bad, don't simply swallow the exception, the stack trace can be very helpful and swallowing it can only hurt you. In your catch class do something like this
This way when exceptions occur you know what happened and you can figure out why it happened and how to fix it.Java Code:try{ //do something risky } catch(Exception e){ e.printStackTrace(); }
Another problem I see, when writing the sorted list you use this line
but as far as I can tell E is only used in a for each loop, and this variable no longer exists when you write it.Java Code:output.println(E + " ");
As a matter of fact, this whole method can use improvement:
You never use the local variable int x, so why have it as a formal parameter? You also only write one line to the file, then close the stream. If any errors occur you swallow them.Java Code:bubbleSort(unsortedArray, unsortedArray.length); /* public void writeFileToDisk(int x) { file = ("students2.txt"); try { File outFile = new File(file); PrintWriter output = new PrintWriter(outFile); output.println(E + " "); output.close(); } catch (Exception error) { }//End Of Error Catching }//End Of Write */Last edited by sunde887; 05-02-2011 at 01:06 AM.
- 05-02-2011, 01:05 AM #9
Member
- Join Date
- May 2011
- Posts
- 10
- Rep Power
- 0
Thanks so much, I will try some of this stuff and post back the results. The error catching is actually code directly from our teacher. So not sure why he would use it like that, oh well I will fix it. Thanks again, soon as I get a second to try it I will post back. Thanks again for all the input.
- 05-02-2011, 01:07 AM #10
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
Make sure to keep checking back, I edit in a lot of useful stuff usually lol.
- 05-02-2011, 01:36 AM #11
Member
- Join Date
- May 2011
- Posts
- 10
- Rep Power
- 0
Thanks so much again, I added the stuff and it does compile now, THANK GOD, you are the man. Now I just have some more things to do with it and we will see if it runs like it should. I will keep you posted.
Another question, what do you know about threads? He gave us a program for Extra Credit that deals with two programs one Bridge class and a Woolie class. The basic idea is there is a troll who controls the bridge from the Bridge class, each Woolie from the Woolie class will need permission from the troll to cross, and only one Woolie allowed on the bridge at a time. The program will notify when the bridge is clear. The handout says the Bridge class will have a enterBridge() method and a leaveBridge() method. And then a run() constructor in the Woolie class. This is all he really gave us and he has never taught us about threads, hence the reason it is extra credit, and I have no clue where to start, well I did, I made the Bridge and Woolie classes with the methods he said they should contain, lol, that is it, so far, any ideas?? Ha , thanks again in advance.
- 05-02-2011, 02:15 AM #12
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
Sadly, I don't know much about threading at the moment. I understand the basics, but not enough to give incredibly confident advice. However; there may be others on this forum who can help you out. I can also link you to the tutorials: Threading Tutorials
To me, threading is one of the more challenging and error prone topics. I can help you, but I can't guarantee my advice will be all to great.
- 05-02-2011, 02:54 AM #13
Member
- Join Date
- May 2011
- Posts
- 10
- Rep Power
- 0
thats ok, any help is appreciated. One other prob with my last program, I cant get the write method to work, here is the code, guess Im not sure what to put in the output.print line
Java Code:import java.io.*; import java.util.*; import java.util.Scanner; public class ReadDataAndSort { public static void main(String [] args) { System.out.println("Welcome to name sorter"); String first = new String(); String last = new String(); //create ArrayList object or Integers String file= new String(); ArrayList<Student> arrList = new ArrayList<Student>(); int count = 0; java.io.File sourceFile = new java.io.File("students.txt"); String temp = new String(); try { Scanner input = new Scanner(sourceFile); while (input.hasNext()) { first = input.next(); last = input.next(); System.out.print("DEBUG statement first-> "+first); //used for debugging System.out.println(" last -> "+last+" \t$$"); //used for debugging Student oneStudent = new Student(last,first); arrList.add(oneStudent); }//end of while loop to read all the data from the disk for (Student E : arrList) System.out.println(E); //verify all the input data was read in from disk input.close();//done reading all the names from disk }//end of try block catch (FileNotFoundException xx) { System.out.println("Error ---> Data file does not exist"); } catch (NumberFormatException xxx) { System.out.println("Error ---> Can NOT parse string data to an integer"); System.out.println("String data is in temp->"+temp); } catch (Exception error) { System.out.println("some RUN-TIME error has occured"); System.out.println("Error ---> "+error); }//end of catch Iterator<Student> it = arrList.iterator(); System.out.println("-------------------------------------"); Student [] unsortedArray = new Student[arrList.size()]; while (it.hasNext()) //create a loop move an arrayList into an array { Student anObj = it.next();//get Object out of ArrayList unsortedArray[count] = anObj; // work on this line of code......; count = count + 1; System.out.println(anObj);//only used for testing }//end of while loop to empty arrayList named arrList for (int i = 0 ; i< unsortedArray.length; ++i) System.out.println(unsortedArray[i]);//debug bubbleSort(unsortedArray,unsortedArray.length); file = ("students2.txt"); try { File outFile = new File(file); PrintWriter output = new PrintWriter(outFile); for (Student E : arrList) output.println(E + " "); output.close(); } catch (Exception error) { }//End Of Error Catching }//end of main method private static void bubbleSort (Student[]unsortedArray,int length) { Student temp; int counter; int index; for (counter = 0; counter<length - 1; counter ++) { for(index = 0; index<length - 1 - counter; index ++) { if(unsortedArray[index] .compareTo(unsortedArray[index + 1]) > 0) { temp = unsortedArray[index]; unsortedArray[index] = unsortedArray[index + 1]; unsortedArray[index + 1] = temp; } }//End Of If Loop For Swap }//End Of Inner Loop } }//end of class
- 05-02-2011, 03:31 AM #14
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
If you used the for-each loop like you did, output.println(E + " "); should work. Have you tried compiling and running this to see what happens?
Also, with the threading stuff, post whatever you need help with and I will do what I can to help out. Others may help as well. There are quite a few people here that are much more intelligent than I(Darryl, fubar, jos, just to name a few of the many)
- 05-02-2011, 03:39 AM #15
Member
- Join Date
- May 2011
- Posts
- 10
- Rep Power
- 0
Ok cool, I will first thing tomorrow. Ya it compiles and runs but it doesnt write to the disk. Not sure why.
- 05-02-2011, 03:07 PM #16
Member
- Join Date
- May 2011
- Posts
- 10
- Rep Power
- 0
Ok the program will still not write to disk with the code that I am using. Not sure why, I will post the code again. Any help will be greatly appreciated. It reads from the file correctly the students.txt but does not write at all to the students2.txt. Thanks
Java Code:import java.io.*; import java.util.*; import java.util.Scanner; public class ReadDataAndSort { public static void main(String [] args) { System.out.println("Welcome to name sorter"); String first = new String(); String last = new String(); //create ArrayList object or Integers String file= new String(); ArrayList<Student> arrList = new ArrayList<Student>(); int count = 0; java.io.File sourceFile = new java.io.File("students.txt"); String temp = new String(); try { Scanner input = new Scanner(sourceFile); while (input.hasNext()) { first = input.next(); last = input.next(); System.out.print("DEBUG statement first-> "+first); //used for debugging System.out.println(" last -> "+last+" \t$$"); //used for debugging Student oneStudent = new Student(last,first); arrList.add(oneStudent); }//end of while loop to read all the data from the disk for (Student E : arrList) System.out.println(E); //verify all the input data was read in from disk input.close();//done reading all the names from disk }//end of try block catch (FileNotFoundException xx) { System.out.println("Error ---> Data file does not exist"); } catch (NumberFormatException xxx) { System.out.println("Error ---> Can NOT parse string data to an integer"); System.out.println("String data is in temp->"+temp); } catch (Exception error) { System.out.println("some RUN-TIME error has occured"); System.out.println("Error ---> "+error); }//end of catch Iterator<Student> it = arrList.iterator(); System.out.println("-------------------------------------"); Student [] unsortedArray = new Student[arrList.size()]; while (it.hasNext()) //create a loop move an arrayList into an array { Student anObj = it.next();//get Object out of ArrayList unsortedArray[count] = anObj; // work on this line of code......; count = count + 1; System.out.println(anObj);//only used for testing }//end of while loop to empty arrayList named arrList for (int i = 0 ; i< unsortedArray.length; ++i) System.out.println(unsortedArray[i]);//debug bubbleSort(unsortedArray,unsortedArray.length); file = ("students2.txt"); try { [COLOR="red"]File outFile = new File(file); PrintWriter output = new PrintWriter(outFile); for (Student E : arrList) output.println(E + " "); output.close();[/COLOR] } catch (Exception error) { }//End Of Error Catching }//end of main method private static void bubbleSort (Student[]unsortedArray,int length) { Student temp; int counter; int index; for (counter = 0; counter<length - 1; counter ++) { for(index = 0; index<length - 1 - counter; index ++) { if(unsortedArray[index] .compareTo(unsortedArray[index + 1]) > 0) { temp = unsortedArray[index]; unsortedArray[index] = unsortedArray[index + 1]; unsortedArray[index + 1] = temp; } }//End Of If Loop For Swap }//End Of Inner Loop } }//end of class
- 05-02-2011, 03:45 PM #17
Member
- Join Date
- May 2011
- Posts
- 10
- Rep Power
- 0
Here is the threading code that I have started. From what my professor says it is basic threading stuff. And like I said, he has taught us nothing about it, that is why it is merely extra credit. I would like to turn it in tomorrow but I have no idea where to go from what I have already. Any help would be appreciated. Here is the synopsis of what is has to do....
The basic idea is there is a troll who controls the bridge from the Bridge class, each Woolie from the Woolie class will need permission from the troll to cross, and only one Woolie allowed on the bridge at a time. The program will notify when the bridge is clear. The handout says the Bridge class will have a enterBridge() method and a leaveBridge() method. And then a run() constructor in the Woolie class.
Here is the bridge class
Here is the woolie classJava Code:import java.io.*; import java.util.*; public class Bridge { public void enterBridge() { }//End Of Enter Bridge Method public void leaveBridge() { }//End Of Leave Bridge Method public static void main (String[] args) { }//End Of Main }//End Of Class
Java Code:import java.io.*; import java.util.*; public class Woolie { public void run() { }//End Of Run Method }//End Of Class
- 05-02-2011, 05:29 PM #18
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
try doing
Not sure if flushing it will help, however; here is the println(Object) summaryJava Code:output.println(E); output.flush();
Java Code:println public void println(Object x) Prints an Object and then terminates the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println(). Parameters: x - The Object to be printed.
- 05-02-2011, 05:37 PM #19
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
To have a thread you want to implement Runnable. So the woolie class should be like this
You are going to probably want to synchronize the enter bridge method. That way once something is on the bridge it will hold the lock to the bridge class. When it exits the bridge it will relinquish the lock, and notifyAll().Java Code:class Woolie implements Runnable{ public void run(){ //do stuff } }
Perhaps the troll will be the one that attempts to acquire a lock and allow a woolie to enter the bridge. When the troll tries to access the bridge, if the lock is available the woolie successfully enter the bridge.
Threading can be a bit more complicated then most other programming. Others here will hopefully tell me if I am sending you down the right path or not. If you are interested in really getting into threading you may want to consider the following book: Java Concurrency in Practice
Similar Threads
-
Read text file and sort in ArrayList
By Tabula Rasa in forum New To JavaReplies: 7Last Post: 04-17-2011, 04:08 AM -
Read/Write Files
By FlyNn in forum New To JavaReplies: 3Last Post: 02-06-2010, 08:45 PM -
How Read and Write XMl files using Java
By tjs in forum SWT / JFaceReplies: 0Last Post: 02-23-2009, 12:19 PM -
How to sort a list using Bubble sort algorithm
By Java Tip in forum AlgorithmsReplies: 3Last Post: 04-29-2008, 08:04 PM -
need help with bubble sort
By lowpro in forum New To JavaReplies: 3Last Post: 12-17-2007, 05:27 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks