-1

I have a basic class FileOutput that will write to a textfile HighScores. I also have a class fileReader that will print out what is written in the textfile. Is there a way to read a line of the textfile HighScores and save it as a String variable? I eventually want to be able to keep track of the top 5 HighScores in a game so I will need a way to compare the latest score to those in the top 5. Here is my code so far:

import java.util.Scanner;
import java.io.File;

 public class FileReader 
 {

public static void main(String args[]) throws Exception
{
    // Read from an already existing text file


    File inputFile = new File("./src/HighScores");
    Scanner sc = new Scanner(inputFile);
    while (sc.hasNext()){
        String s = sc.next();
        System.out.println(s);
    }   

}

FileOutput Class:

import java.io.PrintWriter;
import java.io.FileWriter;
import java.util.ArrayList;

public class FileOutput 
{
    public static void main(String args[]) throws Exception
    {
        FileWriter outFile = new FileWriter("./src/HighScores");
        PrintWriter out = new PrintWriter(outFile);

        // Write text to file
        out.print("Top Five High Scores");
        out.println(50);
        out.println(45);
        out.println(20);
        out.println(10);
        out.println(5);
        out.close(); 
    }
}
Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
Daniel
  • 13
  • 2
  • You don't want a string variable, you want a string *collection*. You already have a string variable. I'd do a quick search for "java list of strings" or something similar to get started. – Dave Newton Feb 19 '15 at 21:27
  • String s=sc.nextLine()? or you want to read a line which contains the 5 top scores and split it to 5 scores? – crAlexander Feb 19 '15 at 21:30
  • possible duplicate of [How to read a large text file line by line using Java?](http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java) –  Feb 19 '15 at 21:36
  • There is a lot of question that get answered about this. http://stackoverflow.com/questions/13533485/is-there-any-way-to-get-the-size-in-bytes-of-a-string-in-java/13536160#13536160 – erhun Feb 19 '15 at 21:40

1 Answers1

0

Yes.

I'm not sure if this is the most clever method of doing so, but you could create an ArrayList and create a collection of strings. Instead of out.print'ing you could try this:

ArrayList<String> al = new ArrayList<>();

    while (sc.hasNext()){
        String s = sc.next();
        al.add(s);
    }  

That will create a list of strings which you could get the top 5 values of later by saying:

String firstPlace = al.get(0);
String secondPlace = al.get(1);
String thirdPlace = al.get(2);
String fourthPlace = al.get(3);
String fifthPlace = al.get(4);
Jud
  • 1,324
  • 3
  • 24
  • 47