1

So essentially, i have a file called highscore.txt with the following in it:

24 01 James 7
24 01 James 11
24 01 James 1234
24 01 James 3
24 01 James 3
24 01 James 41
24 01 James 431
24 01 James 3
24 01 James 2
24 01 James 444
24 01 James 44
24 01 James 876
24 01 James 865
24 01 James 1

[What i want to do, is to create an array with ten 'spaces' (0-9). The ten would be the lines here with the lowest numbers at the end.]

In other words: With array[0] being "24 01 James 1" and array[9] being 24 01 James 444

What i've tried:

FileInputStream fstream = null;
try {
fstream = new FileInputStream("highscore.txt");
} catch (FileNotFoundException ex) {}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;

List<String> list = new ArrayList<String>();

try {
while ((strLine = br.readLine()) != null)   {    
list.add(strLine);} } 
catch (IOException ex) {}

String[] stringArr = list.toArray(new String[0]);

Now, I am not entirely sure what to do:

I was thinking, maybe:

 for(int i = 0; i < stringArr.length; i++){
 String words[] = stringArr[i].split(" "); }

Then, i can use words[3] to check the number at the end?

Anyway, i'd be extremely grateful for any help, i'm not too sure how to approach this, i've only just started Java.

Thanks!

User1
  • 13
  • 2
  • I'd suggest checking out Collections.sort: http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List) You can pass in your own Comparator if you need to look specifically at `words[3]` after a split. – Marc Baumbach Jan 24 '14 at 21:37
  • I see what you mean.... i'll experiment and let you know! – User1 Jan 24 '14 at 21:46
  • I used: Collections.sort(lists); - but it gives this: [1, 11, 1234, 2, 3, 3, 3, 41, 431, 44, 444, 7, 865, 876] I'm not too used to this; how can i make it so it isn't "natural ordering"? – User1 Jan 24 '14 at 22:12

3 Answers3

1

I imagine this is for a game, so you can create a class HighscorePlayer that contains name and score in the constructor. Then you can feed it the information directly from words[] and store it in an array of the same size as stringArr[]. You may need to use Integer.parseInt(string) to convert the string to an int. That will give you an array of HighscorePlayers, each containing a name and score.

Now you need to be able to sort the players by their score value. To do this HighscorePlayer will need to implement Comparable

class HighscorePlayer implements Comparable<HighscorePlayer>{
    public int score;
    public String name;

    public HighscorePlayer(String name, int score){
        this.name = name;
        this.score = score;
    }

    @Override
    public int compareTo(HighscorePlayer player) {
        return Integer.compare(score, player.score);
    }
}

Then you can just run an Arrays.sort(players) and iterate through that array. That will let you keep the name associated with the score, as well as allowing you room to add more associated information should you need to.

Zabot
  • 36
  • 4
1

If you really just need the score, here's what I'd suggest:

...
catch(IOException ex){}
String[] stringArr = new String[list.size()];
stringArr = list.toArray(stringArr);
int score[] = new int[stringArr.length];

for(int i = 0; i < score.length; i++){
    for (String strScore : stringArr[i].split("24 01 James "))
    {
       score[i] = Integer.parseInt(strScore);
    }
 }

Now you have all the scores stored in an integer array. Just do a sort in ascending order and take the first 10 elements :)

Here are some sources I used to answer your question:

http://www.tutorialspoint.com/java/number_parseint.htm

http://www.tutorialspoint.com/java/java_string_length.htm

Convert ArrayList<String> to String[] array (Most important one)

Community
  • 1
  • 1
1

I thought using Object was the only way to go, because it allows to store different types in it. This was desirable for the sorting of the object array since sorting int's can't go wrong.

public class JavaApplication9 {

    static private ReadFile readFile;

    public static void main(String[] args) {
        readFile = new ReadFile();
        readFile.readnewFile();
        readFile.wordRead();
        readFile.convertToObject();
        readFile.sortIng();
        readFile.display();
    }
}

second file:

public class WordsClass {

    final public Object[][] finalTest;
    private int nElems;

    public WordsClass(String theDay, String theMonth, String theName, String theScore) {
        finalTest = new Object[14][4];
        nElems = 0;
    }

    public Object myObject(String a, String b, String c, String d) {
        finalTest[nElems][0] = Integer.parseInt(a);
        finalTest[nElems][1] = Integer.parseInt(b);
        finalTest[nElems][2] = c;
        finalTest[nElems][3] = Integer.parseInt(d);
        nElems++;
        return finalTest;
    }
}

and third file:

public class ReadFile {

    static private FileInputStream fstream;
    static private DataInputStream in;
    static private BufferedReader br;
    static private String strLine;
    static private Object[][] words;
    static private int nElems;

    WordsClass wordsClass = new WordsClass(null, null, null, null);

    public ReadFile() {
        words = new Object[14][4];
        nElems = 0;
    }

    public void readnewFile() throws FileNotFoundException {
        fstream = new FileInputStream("highscore.txt");
        in = new DataInputStream(fstream);
        br = new BufferedReader(new InputStreamReader(in));
        // wordRead(); 
    }

    public Object wordRead() throws IOException {
        try {
            while ((strLine = br.readLine()) != null) {
                words[nElems] = strLine.split(" ");
                nElems++;
            }
        } catch (IOException e) {
        }
        br = null;
        in = null;
        fstream = null;
        return words;
    }

    public Object convertToObject() {

        for (Object[] word : words) {
            wordsClass.myObject(word[0].toString(), word[1].toString(), 
                   word[2].toString(), word[3].toString());
        }
        words = null;
        return wordsClass;
    }

    public boolean sortIng() {
        Arrays.sort(wordsClass.finalTest, new Comparator<Object[]>() {
            @Override
            public int compare(final Object[] w1, final Object[] w2) {
                final Integer a = Integer.parseInt(w1[3].toString());
                final Integer b = Integer.parseInt(w2[3].toString());
                return a.compareTo(b);
            }
        });
        return true;
    }

    public void display() {
        for (Object[] finalTest : wordsClass.finalTest) {
            for (Object finalTest1 : finalTest) {
                System.out.print(finalTest1 + " ");
            }
            System.out.println("");
        }
    }
}

All this gives an output of:

  • 24 1 James 1
  • 24 1 James 2
  • 24 1 James 3
  • 24 1 James 3
  • 24 1 James 3
  • 24 1 James 7
  • 24 1 James 11
  • 24 1 James 41
  • 24 1 James 44
  • 24 1 James 431
  • 24 1 James 444
  • 24 1 James 865
  • 24 1 James 876
  • 24 1 James 1234

Since sorting by String didn't work as wanted. It sorted ok, but it gave the wrong result. It sorted at 1's, so 1, 11, 1234, 2 etc.

With thanks to this CompareTo/Sorting 2D array of Strings AND Integers topic. Which helped me figuring Object sorting out.

edit: I cleaned up a bit. It is good practice to keep main as clean as possible and only use it for calls to methods in other classes. Added private and public to reference's, and set a few things to null that weren't needed anymore after their usage. All this speeds up performance. (a lot).

Community
  • 1
  • 1
WonderWorld
  • 956
  • 1
  • 8
  • 18