cant sort larger numbers with .sort()

edited October 2017 in Questions about Code

I want to sort a table, so I use the .sort(); function but when I save the table it looks like this:

1
1116
1232
206
2375
281
356
468
736

it seems like it sorts based on the first number and just acts like all the other numbers are decimal points, have I done something wrong?

Answers

  • edited October 2017

    How are your numbers stored? As numbers? Or... Strings?

  • @TfGuy44 They are stored as Intergers.

  • Are you sure? Let's see the code for that then.

  • edited October 2017

    Its part of a larger code but here are the functions that matter to the question

    Table highscoreRegister;
    
    void setup() {
      highscoreRegister = loadTable("data/Highscores.csv", "header");
    }
    
    //void score is called when a string comes in with "score" in it
    void score(String incomingMessage) {
      //gets player's score form the string
      int currentScore = getScore(incomingMessage);
      //gets player's id (username)
      String currentId = getId(incomingMessage);
    
      //adds user id and score to the table
      addNewScore(currentId, currentScore);
      //saves table to a file
      saveUserHighscores();
    }
    
    void saveUserHighscores() {
      highscoreRegister.sortReverse("points");
      saveTable(highscoreRegister, "data/Highscores.csv");
    }
    
    int getScore(String incomingMessage) {
      int firstSign = 0;
      int secondSign = 0;
      for (int i = 0; i < incomingMessage.length(); i ++) {
        if (incomingMessage.charAt(i) == '/') firstSign = i + 2;
        if (incomingMessage.charAt(i) == 'i') secondSign = i - 1;
      }
    
      String tempScore = incomingMessage.substring(firstSign, secondSign);
      return int(tempScore);
    }
    
    void addNewScore(String currentId, int currentScore) {
      TableRow newHighscoreRow = highscoreRegister.addRow();
      newHighscoreRow.setString("name", currentId);
      newHighscoreRow.setInt("points", currentScore);
    }
    

    Here's a link to the highscore.csv file https://drive.google.com/file/d/0B5_vyYKbiszELUFHa1JJaGJZQ3c/view?usp=sharing

  • @GoToLoop thank you, highscoreRegister.setColumnType("points", Table.INT); does the job :D

  • @schotsl -- so to be clear, @TfGuy44 was right -- they were being sorted as strings / alphabetized, because of the default Table field type. There was no mysterious hidden decimal thing.

Sign In or Register to comment.