请帮忙。我试图让程序访问名为“highscore.txt”的文件,然后:
1:在文件中写一个新号码
2:获取文件中数字列表的最低值。
如果您知道如何,请发布代码。
***注意:我是Java的新手,所以我几乎不知道如何访问文件***
编辑:
我得到了我认为应该有效的代码,但是当我运行该程序时,它会说
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at game.game.main(game.java:91)
Java Result: 1
这是第84-94行,以及我得到的代码。
84: Writer wr = new FileWriter("highscore.txt");
85: wr.write(tries);
86: wr.close();
87: lowest = tries;
88: File file = new File("highscore.txt");
89: Scanner inputFile = new Scanner(file);
90: while (inputFile.hasNext()) {
91: numb = inputFile.nextDouble();
92: if (numb < lowest) lowest = number;
93: }
94: inputFile.close();
编辑:
我有点工作。有一个错误,它只是在文本文件中放置一个随机的Unicode符号。 以下是该部分的代码:
try {
int content = tries;
File file = new File("highscore.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Writer wr = new FileWriter("highscore.txt");
wr.write(tries);
wr.close();
lowest = tries;
File file = new File("highscore.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNextInt()) {
numb = inputFile.nextInt();
if (numb < lowest) lowest = numb;
}
文件:
32
12
7
9
18
66
13
17
91
答案 0 :(得分:0)
试试这个..
int tries = 8;
// Writing to the file
try {
int content = tries;
File file = new File("highscore.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
PrintWriter pw = new PrintWriter(new FileWriter(file, true));
pw.println(content);
pw.close();
/*
* FileWriter fw = new FileWriter(file.getAbsoluteFile());
* BufferedWriter bw = new BufferedWriter(fw); bw.write(content);
* bw.close();
*/
} catch (IOException e) {
e.printStackTrace();
}
/*
* Writer wr; try { wr = new FileWriter("highscore.txt");
* wr.write(tries); wr.close(); } catch (Exception e) {
*
* }
*/
// Getting the minimum score from the file
int lowest = tries;
File file = new File("highscore.txt");
Scanner inputFile;
try {
inputFile = new Scanner(file);
while (inputFile.hasNextInt()) {
int numb = inputFile.nextInt();
if (numb < lowest)
lowest = numb;
}
System.out.println("lowest Score is: " + lowest);
} catch (FileNotFoundException e) {
e.printStackTrace();
}