-
Problem in java
I've got a problem with a score list. I am diplaying the scores of all the users who enter the game. The problem is that the score are not listed in an alligned form. The player names are displayed in a good way, but the scores are either displayed as only one word (i.e the score joined with the word example John90 or else when i tried to include a space between the name and the score, the scores are not displayed in an alligned form (they depend on the length of the name) eg:
John 90
Raymond 80
Jake 10
Charmaine 90
This is the piece of code used to display this (this is being displayed on a dialog box, and the text is called from a textfile to a TextArea):
Code:
try {
JOptionPane.showMessageDialog(null, "You answered " + count +
" out of " + questions.length +
" questions correctly.");
BufferedWriter out;
String text = JOptionPane.showInputDialog(null, "Enter your name");
out = new BufferedWriter(new FileWriter("players.txt",true));
out.write(text);//Write out a string to the text file
out.write(" "); // i tried to use this to make a space, but its making a space depending on the length of the player name
out.write(String.valueOf(count));
out.newLine();
out.close();
}catch(IOException e){
System.out.println("There was a problem:" + e);
}
Thanks for the help.
-
Code:
// Instead of :: out.write(" "); // i ..
out.write(getSpace(20- text.length())); // Here 20 is max length possible change accordingly
...
public static String getSpace(int length){
String str = "";
for(int i = 0 ; i < length ; i++ ){
str = str + " " ;
}
return str ;
}
Should align the score ..
-
Hi thanks a lot for your response. I have understood what you have written, but it seems that its doing the same thing (i.e not alligning the score).
Thanks.
-
you can apply trim() to player's name .. and above code should work provided that the you use maximum possible length of name instead of 20.
Delete the existing data file as well.
-