[英]Saving points to file Java
老實說,我找不到任何可以回答我的問題的帖子,如果我有〜4場游戲需要用戶輸入賭注,並且如果贏了,我如何每次省下那筆新錢? 所以,如果我有很多if陳述,例如骰子游戲
if (UserPlay.equals(ComputerPlay))
{
System.out.print("Tie");
}
else if (UserPlay == "Rock" && ComputerPlay == "Paper" )
{
System.out.print("Computer wins");
money = money - (bet * 2);
}
else if (UserPlay == "Rock" && ComputerPlay == "Scissors")
{
System.out.print("You win");
money = money + (bet * 2);
}
.... etc
我將如何繼續更新我的文件以覆蓋先前的金額,以便如果用戶退出並再次進入游戲,則金額將保持不變。
嘗試使用equals
方法而不是==
像這樣:
else if ("Rock".equals(UserPlay) && "Paper".equals(ComputerPlay))
...
else if ("Rock".equals(UserPlay) && "Scissors".equals(ComputerPlay))
...
了解Equals Vs ==的更多詳細信息
為了將數據保存到文件中並再次讀取,可以嘗試以下操作:
// when write
OutputStream out = new FileOutputStream(new File("data.txt"));
out.write(String.valueOf(money).getBytes());
out.close();
try {
// and when read, it is better to put it in the try catch block
// maybe for the first time cannot find the file
InputStream in = new FileInputStream(new File("data.txt"));
byte[] b = new byte[1024];
in.read(b);
in.close();
money = Integer.parseInt(new String(b));
} catch (IOException e) {
e.printStackTrace();
}
您可以創建一個文件來將所有信息成對保存在玩家貨幣中,並在需要時讀取/重寫。 如果玩家再次登錄-您只需要在文件中找到他,然后讀取貨幣值即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.