Results 1 to 3 of 3
Thread: Sorting Elements From a File
- 10-01-2013, 08:54 PM #1
Senior Member
- Join Date
- Aug 2013
- Location
- Sweden
- Posts
- 163
- Rep Power
- 8
Sorting Elements From a File
Hello!
I put some names and scores into a file called "hej.txt", like this:
Random1
10
Random2
20
Random3
30
etc.
Java Code:import java.util.Scanner; import java.io.*; public class Ostbågar{ public static void main(String[] args){ File file = new File("hej.txt"); try{ Scanner hej = new Scanner(file); int rader = 0; while(hej.hasNext()){ String s = hej.nextLine(); if(s == null) break; rader++; } hej = new Scanner(file); if(rader > 1 && rader % 2 == 0){ String namn[] = new String[rader/2]; int scores[] = new int[rader/2], x = 0, y = 0; while(hej.hasNext()){ String s = hej.nextLine(); if(s == null) break; namn[x] = s; s = hej.nextLine(); scores[y] = Integer.parseInt(s); x++; y++; } while(x<(scores.length-1)){ for(y=0;y<scores.length-1;y++){ // SORTING THE ELEMENTS HERE! if(scores[y] < scores[y+1]){ int temp = scores[y]; scores[y] = scores[y+1]; scores[y+1] = temp; String grej = namn[y]; namn[y] = namn[y+1]; namn[y+1] = grej; } } x++; } System.out.print(namn[0] + " had the highest score with " + scores[0] + "!"); }else System.out.print("Error reading file!"); }catch(FileNotFoundException e){ } } }
- 10-01-2013, 09:15 PM #2
Senior Member
- Join Date
- Jan 2013
- Location
- Northern Virginia, United States
- Posts
- 6,226
- Rep Power
- 15
Re: Sorting Elements From a File
I'm not certain I understand. How do you know your sort doesn't work if you already put them in sorted order? Or am I not understanding something?
Edit: Ok, after looking at your code, you need to reset x to 0 before your while statement of your sort loop.
Regards,
JimLast edited by jim829; 10-01-2013 at 09:22 PM.
The JavaTM Tutorials | SSCCE | Java Naming Conventions
Poor planning on your part does not constitute an emergency on my part
- 10-01-2013, 09:46 PM #3
Senior Member
- Join Date
- Aug 2013
- Location
- Sweden
- Posts
- 163
- Rep Power
- 8
Similar Threads
-
Writing the elements of a TreeMap to a text file
By busdude in forum New To JavaReplies: 0Last Post: 10-03-2011, 04:05 AM -
Swapping/Sorting elements in an Array
By kumalh in forum New To JavaReplies: 2Last Post: 08-10-2011, 05:52 AM -
sorting data in txt file
By cassysumandak in forum New To JavaReplies: 1Last Post: 04-12-2009, 04:02 AM -
Sorting xml file
By keioGirl in forum Advanced JavaReplies: 4Last Post: 12-12-2008, 06:14 PM -
Sorting Elements in a TreeMap
By Java Tip in forum java.langReplies: 0Last Post: 04-12-2008, 09:47 PM
Bookmarks