我刚刚开始学习 Java,我正在尝试使用我的方法之一从主类读取数组,而主类又从文件中获取其值。该文件只是前 5 个分数列表,名称和数字用一行分隔。我正在制作的方法需要检查给予它的分数是否高于该位置已有的分数并替换该分数。唯一的问题是我无法从我的方法访问数组值。
这是我的代码:
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()
{
}
*/
最佳答案
在类中定义数组,而不是在 main 方法本身中。
关于JAVA 无法在 main from 方法中访问我的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35161667/