-
Problem
I have a list of scores stored in a textfile. I need to sort these numbers, with the highest on top. I don't know how to call these numbers into an array. Can someone pls show me how to call and sort the numbers please. Thanks a lot. I have to use a kind of algorithm sorting (like bubble sort) not using the Collections class.
-
You can do this with the Scanner class or with a Reader.
Code:
import java.io.*;
import java.util.Arrays;
public class ReadToArray {
public static void main(String[] args) throws IOException {
String path = "readToArray.txt";
File file = new File(path);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(file)));
String line;
while((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
String[] items = sb.toString().split("\\n");
System.out.printf("items = %s%n", Arrays.toString(items));
}
}
readToArray.txt
Code:
1000
35
9920
212
52
-
Ok thanks a lot. But the problem is that in this texfile i have stored not only the scores but also the names since this is like a quiz and it is displaying the high score.
This is the piece of code that displaysthe high scores together with the names. Can you pls help me, in making the scores being sorted with the highest mark displayed on top together with the names.
Thanks a lot. :-)
This is the code that displays the scores and names from textfile:
Code:
import java.awt.BorderLayout;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import javax.swing.JDialog;
import javax.swing.JTextArea;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.Arrays;
public class Scores {
private JTextArea textArea;
public Scores() {
super();
try{
JDialog dialog = new JDialog();
dialog.getContentPane().setLayout(new BorderLayout(10, 10));
//
String record = null;
String path = "players.txt";
File file = new File("players.txt");
FileInputStream fileInput = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fileInput);
String string = dis.readLine();
textArea = new JTextArea();
while(string != null){
textArea.append(string + "\n");
string = dis.readLine();
textArea.setBackground(Color.orange);
textArea.setFont(new Font("Times New Roman", Font.BOLD, 14));
textArea.setEditable(false);
textArea.setForeground(Color.red);
}
dialog.getContentPane().add(BorderLayout.CENTER, textArea);
dialog.setTitle("Scores");
dialog.setSize(350, 350);
dialog.setVisible(true);
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
new Scores();
}
}
And this code is used to write the names together with the score to the textfile:
Code:
String name = JOptionPane.showInputDialog(null, "Enter name");
String type = JOptionPane.showInputDialog(null, "Enter your quiz type");
out = new BufferedWriter(new FileWriter("players.txt",true));
out.write(name); //Writing to the textfile (the name entered by user)
String trimmedStr = name.trim();
out.write(String.valueOf(percent+ " % "));
out.write(" ");
out.newLine(); //write a new line to the textfile
out.close();
I tried doing somethig like this, but it isn't working.
Code:
import java.awt.BorderLayout;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import javax.swing.JDialog;
import javax.swing.JTextArea;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.Arrays;
public class Scores {
int len;
private JTextArea textArea;
public Scores() {
super();
try{
JDialog dialog = new JDialog();
dialog.getContentPane().setLayout(new BorderLayout(10, 10));
//
String record = null;
String path = "players.txt";
File file = new File(path);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(file)));
String line;
while((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
String[] p = sb.toString().split("\\n");
System.out.printf("items = %s%n", Arrays.toString(p));
int a,b;
String temp;
int sortTheStrings = len - 1;
for (a = 0; a < sortTheStrings; ++a)
for (b = 0; b < sortTheStrings; ++b)
if(p[b].compareTo(p[b + 1]) >0)
{
temp = p[b];
p[b] = p[b + 1];
p[b + 1] = temp;
}
FileInputStream fileInput = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fileInput);
String string = dis.readLine();
textArea = new JTextArea();
while(string != null){
textArea.append(string + "\n");
string = dis.readLine();
textArea.setBackground(Color.orange);
textArea.setFont(new Font("Times New Roman", Font.BOLD, 14));
textArea.setEditable(false);
textArea.setForeground(Color.red);
}
dialog.getContentPane().add(BorderLayout.CENTER, textArea);
dialog.setTitle("Scores");
dialog.setSize(350, 350);
dialog.setVisible(true);
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
new Scores();
}
}
Thanks a lot again. :-)
-
Here's how I would do things in your first two code blocks above.
Code:
import java.awt.*;
import java.io.*;
import javax.swing.*;
public class ScoresRx {
private void readFile() {
// Creat textArea to show file data.
JTextArea textArea = new JTextArea();
textArea.setBackground(Color.orange);
textArea.setFont(new Font("Times New Roman", Font.BOLD, 14));
textArea.setEditable(false);
textArea.setForeground(Color.red);
// Read the file and write to textArea.
String path = "scoresRx.txt";
BufferedReader br = null;
try {
File file = new File(path);
br = new BufferedReader(
new InputStreamReader(
new FileInputStream(file)));
String string = br.readLine();
while(string != null){
textArea.append(string + "\n");
string = br.readLine();
}
} catch(IOException e) {
System.out.println("read error: " + e.getMessage());
} finally {
if(br != null) {
try {
br.close();
} catch(IOException e) {
System.out.println("closing br: " + e.getMessage());
}
}
}
// Show the textArea in a dialog.
JDialog dialog = new JDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.getContentPane().setLayout(new BorderLayout(10, 10));
dialog.getContentPane().add(BorderLayout.CENTER, textArea);
dialog.setTitle("Scores");
dialog.setSize(350, 350);
dialog.setVisible(true);
}
private void writeToFile() {
String[] names = { "John", "Karen", "Samuel", "Mary" };
int[] scores = { 75, 90, 88, 95 };
BufferedWriter out = null;
try {
out = new BufferedWriter(
new FileWriter("scoresRx.txt", true));
for(int j = 0; j < names.length; j++) {
out.write(names[j]);
out.write(" ");
out.write(String.valueOf(scores[j]));
out.newLine();
}
} catch(IOException e) {
System.out.println("write error: " + e.getMessage());
} finally {
if(out != null) {
try {
out.close();
} catch(IOException e) {
System.out.println("closing out: " + e.getMessage());
}
}
}
}
public static void main(String[] args){
ScoresRx app = new ScoresRx();
app.readFile();
}
}
Using DataInput/OutputStreams is a pain. Here is how you deal with deprecation warnings given by the compiler:
Code:
C:\jexp>javac scoresrx.java
Note: scoresrx.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
C:\jexp>javac -Xlint:deprecation scoresrx.java
scoresrx.java:23: warning: [deprecation] readLine() in java.io.DataInputStream has been de
precated
String string = dis.readLine();
^
scoresrx.java:26: warning: [deprecation] readLine() in java.io.DataInputStream has been de
precated
string = dis.readLine();
^
2 warnings
C:\jexp>
-
Here's how I would do things in your third code block above.
Code:
import java.awt.*;
import java.io.*;
import java.util.Arrays;
import javax.swing.*;
public class ScoresRx {
private String readFile() {
// Read the file and save data.
String path = "scoresRx.txt";
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try {
File file = new File(path);
br = new BufferedReader(
new InputStreamReader(
new FileInputStream(file)));
String line;
while((line = br.readLine()) != null) {
sb.append(line + "\n");
}
} catch(IOException e) {
System.out.println("read error: " + e.getMessage());
} finally {
if(br != null) {
try {
br.close();
} catch(IOException e) {
System.out.println("closing br: " + e.getMessage());
}
}
}
return sb.toString();
}
private String[] sort(String data) {
String[] items = data.split("\\n");
for(int j = 0; j < items.length; j++) {
String item = items[j];
int lowIndex = j;
Integer lowScore = getScore(item);
for(int k = j+1; k < items.length; k++) {
String next = items[k];
Integer nextScore = getScore(next);
if(lowScore.compareTo(nextScore) < 1) {
lowIndex = k;
lowScore = nextScore;
}
}
if(lowIndex != j) {
items[j] = items[lowIndex];
items[lowIndex] = item;
}
}
return items;
}
private Integer getScore(String line) {
int pos = line.length();
while(Character.isDigit(line.charAt(pos-1))) {
pos--;
}
return Integer.valueOf(line.substring(pos));
}
private void showData(String[] lines) {
// Creat textArea to show data.
JTextArea textArea = new JTextArea();
textArea.setBackground(Color.orange);
textArea.setFont(new Font("Times New Roman", Font.BOLD, 14));
textArea.setEditable(false);
textArea.setForeground(Color.red);
// Write the lines to the textField.
for(int j = 0; j < lines.length; j++)
textArea.append(lines[j] + "\n");
// Show the textArea in a dialog.
JDialog dialog = new JDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.getContentPane().setLayout(new BorderLayout(10, 10));
dialog.getContentPane().add(BorderLayout.CENTER, textArea);
dialog.setTitle("Scores");
dialog.setSize(350, 350);
dialog.setVisible(true);
}
public static void main(String[] args){
ScoresRx app = new ScoresRx();
String data = app.readFile();
String[] sortedLines = app.sort(data);
app.showData(sortedLines);
}
}
-
Thanks a lot. I have a problem with the 3rd block of code, because its displaying an StringIndexOutOfBoundsException. It is compiling but it isn't executing.
The type of data i have stored in the textfile is like this:
Code:
Mary 75
James 90
Joseph 50
Marianne 63
Thanks a lot. Tou are really helpful. Thanks again. :-)