1

good day!who any one can help on how to sort data from my name.txt

test.text

cath zeny ana dana maria sheila

heres my code:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;

import java.io.IOException;

public class ReadTextFileExample {

public static void main(String[] args) {

File file = new File("name.txt");

StringBuffer contents = new StringBuffer();

BufferedReader reader = null;

try {

reader = new BufferedReader(new FileReader(file));

String text = null;




while ((text = reader.readLine()) != null) {
contents.append(text).append(System.getProperty("line.separator"));

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (reader != null) {

reader.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}


System.out.println(contents.toString());
}
}
1
  • 2
    Try using the code formatting tool in the future. Also, I happen to know this is a homework assignment, so you need to make an attempt to solve it yourself first. I'll give you a hint and say you need an array. Commented Mar 29, 2011 at 5:13

3 Answers 3

4

Put the strings into a list:

List<string> strings = new ArrayList<string>();
while ((text = reader.readLine()) != null) {
    strings.add(text);
}  

Sort the strings:

Collections.sort(strings);  

Do whatever with the sorted strings, like concatenating in a single line:

StringBuffer contents = new StringBuffer();
for (string s : strings) {
    contents.append(text).append(System.getProperty("line.separator"));
}
Sign up to request clarification or add additional context in comments.

Comments

0
//Stores cath zeny ana diana etc in a String array
String[] names=contents.split(System.getProperty("line.seperator"));

//bubble sort
for(int i=0;i<names.length;i++)
   for(int j=0;j<names.length;j++)
   {
      int compare=names[i].compareTo(names[j]);
      if(compare > 0 )
         //swap names[i] and names[j]
      else
         //do nothins
   }

The above code should sort all the names in this array.

Comments

0

sorry, don't have much time to explain ...

you could put all your strings into a linkedlist or arraylist and use the Collections.sort( List lst ) method to sort them.

greetings

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.