gpt4 book ai didi

java - 导入控制台时外部 .txt 文件的值不同

转载 作者:行者123 更新时间:2023-12-01 18:00:46 26 4
gpt4 key购买 nike

我从 .txt 文件中引入值并将它们放入数组中,但最终存储在数组中的数字与文件中的数字不同,我不明白为什么或如何修复它。

文本文件使用这些值进行布局

2
20.0
10.0
100

将值导入文件的方法是:

//variables global to the class
public static int level;
public static int hp;
public static double vigor;
public static double intelligence;

public static void checkSaveState() throws IOException
{
//this method checks the save file for data
try
{
double[] savedGa = new double[4];
BufferedReader saveFile = new BufferedReader(new FileReader("HRHeroSaveGame.txt"));
for (int i = 0; i < 4; i++)
{
savedGa[i] = saveFile.read();
}
level = (int) savedGa[0];
vigor = savedGa[1];
intelligence = savedGa[2];
hp = (int) savedGa[3];

System.out.println("Level: " + level + " Vigor: " + vigor + " Intelligence: " + intelligence + " HP: " + hp);
} catch (FileNotFoundException e) {
System.out.println("Sorry, a save file couldn't be found for you.");
}

}

输出总是这样结束:

Level: 50 Vigor: 13.0 Intelligence: 10.0 HP: 50

以防万一这是相关的,这是创建文件的方法。

public static void saveGame() throws IOException
{
PrintWriter saveFile = new PrintWriter( new FileWriter("HRHeroSaveGame.txt"));
saveFile.println(level);
saveFile.println(vigor);
saveFile.println(intelligence);
saveFile.println(hp);
saveFile.close();
}

最佳答案

read() 读取单个字符。这解释了您的结果:'2' = 50,'\r' = 13,'\n' = 10

您必须将每一行读取为String并解析它以获取 double :

savedGa[i] = Double.parseDouble(saveFile.readLine());

关于java - 导入控制台时外部 .txt 文件的值不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41125742/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com