I'm just starting out Java and I am trying to get one of my methods to read an array from the main class, which in turn gets its values from a file. The file is simply a top 5 scores list, with names and numbers separated by a line. The method I'm making needs to check if the score given to it is higher than the score already in that place and replace that amount. The only problem is I cannot access the array value from my method.
Here is my code:
public static void main(String[] args) {
String [] nameArray = new String[5];
int [] scoreArray = new int[5];
File score = new File("score.txt");
if (score.exists())
{
try {
nameArray[0] = Files.readAllLines(Paths.get("score.txt")).get(0);
nameArray[1] = Files.readAllLines(Paths.get("score.txt")).get(2);
nameArray[2] = Files.readAllLines(Paths.get("score.txt")).get(4);
nameArray[3] = Files.readAllLines(Paths.get("score.txt")).get(6);
nameArray[4] = Files.readAllLines(Paths.get("score.txt")).get(8);
scoreArray[0] = Integer.parseInt(Files.readAllLines(Paths.get("score.txt")).get(1));
scoreArray[1] = Integer.parseInt(Files.readAllLines(Paths.get("score.txt")).get(3));
scoreArray[2] = Integer.parseInt(Files.readAllLines(Paths.get("score.txt")).get(5));
scoreArray[3] = Integer.parseInt(Files.readAllLines(Paths.get("score.txt")).get(7));
scoreArray[4] = Integer.parseInt(Files.readAllLines(Paths.get("score.txt")).get(9));
} catch (IOException ex) {
System.out.println("FILE IO EXCEPTION");
}
}
if (!score.exists())
{
nameArray[0] = "---";
nameArray[1] = "---";
nameArray[2] = "---";
nameArray[3] = "---";
nameArray[4] = "---";
scoreArray[0] = 0;
scoreArray[1] = 0;
scoreArray[2] = 0;
scoreArray[3] = 0;
scoreArray[4] = 0;
BufferedWriter outputWriter;
try {
outputWriter = new BufferedWriter(new FileWriter("score.txt"));
// I am aware I could have used a loop to do this
outputWriter.write(nameArray[0]);
outputWriter.newLine();
outputWriter.write(Integer.toString(scoreArray[0]));
outputWriter.newLine();
outputWriter.write(nameArray[1]);
outputWriter.newLine();
outputWriter.write(Integer.toString(scoreArray[1]));
outputWriter.newLine();
outputWriter.write(nameArray[2]);
outputWriter.newLine();
outputWriter.write(Integer.toString(scoreArray[2]));
outputWriter.newLine();
outputWriter.write(nameArray[3]);
outputWriter.newLine();
outputWriter.write(Integer.toString(scoreArray[3]));
outputWriter.newLine();
outputWriter.write(nameArray[4]);
outputWriter.newLine();
outputWriter.write(Integer.toString(scoreArray[4]));
outputWriter.newLine();
outputWriter.flush();
outputWriter.close();
} catch (IOException ex) {
System.out.println("FILE IO EXCEPTION");
}
}
}
static void playerScore(String name, int score)
{
if (score > scoreArray[0])
{
scoreArray[0] = score;
}
//etc...
}
/* static String [] getTopNames()
{
}
static int [] getTopScores()
{
}
*/