我正在为一项任务创建一个硬币翻转游戏,可以保存您的最后一个高分和名字。如果没有高分文件,程序可以正常工作,但如果有文件,程序就会停止工作。
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
public class BradySkuza43
{
public static void main( String[] args ) throws Exception
{
Scanner keyboard = new Scanner(System.in);
String coin, again, bestName, saveFile = "coin-flip-score.txt";
int flip, streak = 0, best;
File in = new File(saveFile);
if ( in.createNewFile() )
{
System.out.println("Save game file doesn't exist. Created.");
best = 1;
bestName = " ";
}
else
{
Scanner input = new Scanner(in);
bestName = input.next();
best = input.nextInt();
input.close();
System.out.println("High score is " + best + " flips in a row by " + bestName );
}
do
{
flip = 1 + (int)(Math.random()*2);
if ( flip == 1 )
{
coin = "HEADS";
}
else
{
coin = "TAILS";
}
System.out.println( "You flip a coin and it is... " + coin );
if ( flip == 1 )
{
streak++;
System.out.println( "\tThat's " + streak + " in a row...." );
System.out.print( "\tWould you like to flip again (y/n)? " );
again = keyboard.next();
}
else
{
streak = 0;
again = "n";
}
} while ( again.equals("y") );
System.out.println( "Final score: " + streak );
if ( streak > best )
{
System.out.println("That's a new high score!");
System.out.print("Your name: ");
bestName = keyboard.next();
best = streak;
}
else if ( streak == best )
{
System.out.println("That ties the high score. Cool.");
}
else
{
System.out.println("You'll have to do better than " + streak + "if you want a high score.");
}
PrintWriter out = new PrintWriter( new FileWriter(saveFile) );
out.println(bestName);
out.println(best);
out.close();
}
}
当有文件存在时,我收到NoSuchElement错误。我假设它与导入函数有关,但我不知道如何解决它。
答案 0 :(得分:1)
您阅读的方式' best'当已经有文件('最佳'值)似乎不正确时。您可能正在寻找类似的内容(根据您的数据进行修改)以阅读“保存的最佳价值”。
BufferedReader reader = new BufferedReader(new FileReader(in));
String readNumber = "";
while (reader.readLine() != null) {
readNumber += reader.readLine();
}
best = Integer.valueOf(readNumber);
答案 1 :(得分:1)
结束必须只运行代码以查看如何生成savefile。看到来自文件的第二次读取(input.nextInt())的NoSuchElement异常指向该问题。
如果你没有击败现有的连胜(包括将TAILS作为你的第一次翻转),你就不会被提示输入名字。这使得保存文件读取
\n
1
\n
默认情况下,扫描程序会忽略空格。您不检查是否有可用的输入(hasNext方法)。当没有输入时调用next()或nextInt(),你会得到NoSuchElement。为什么这会从保存中发生?
逐行:
bestName = input.next(); <-- This is getting the "1" since there is a name saved
best = input.nextInt(); <-- since the 1 was already read, so there's nothing to get
在获得初始TAILS后,使用savefile的第二个输入正在导致崩溃。
两个解决方案,确保您在main的末尾获取并保存bestName中的bestName,或者在阅读savefile时要更加小心。
(适用编辑)强> 通常,在使用Scanner(或任何具有hasNext()/ next()样式的API时),最好在每个next()之前调用并检查hasNext()。这将确保您从下一个()获得一些东西。
即使你认为没有可能存在某些东西的原因,也可以使用
if(!foo.hasNext) {
System.out.println("foo should really have something here, but hasNext says it doesn't);
System.exit();
}
如果出现问题,将阻止您的代码进入其轨道,并停止添加一些调试语句以查看正在进行的操作。
答案 2 :(得分:0)
以下是一些建议:
static final
变量。getHighScore()
方法(可以是static
)。static writeHighScore(final String name, final int score)
。所以我会把你的程序变成更像这样的东西:
public class BradySkuza43
{
public static final String HIGH_SCORE_FILE = "coin-flip-score.txt";
public static void main( String[] args ) throws Exception
{
final Scanner keyboard = new Scanner(System.in);
final int highScore = getHighScore();
final int newScore = getScore(keyboard);
if(newScore != 0 && newScore > highScore){
final String name = getName(keyboard);
writeHighScore(name, newScore);
}
private static int highScore(){
// read high score from high score file or return Integer.MIN_VALUE if
// no high score file exists
}
private static int getScore(final Scanner keyboard){
// play game, prompt user, get input, etc. and then
// return the player's score.
}
private static String getName(final Scanner keyboard){
// prompt the user for their name and return their input
}
private static void writeHighScore(final String name, final int score){
// write this high score (with the name) to the high score file
}
}