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

时间:2016-12-13 16:18:36

标签: java arrays file filereader

我从.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();
}

2 个答案:

答案 0 :(得分:3)

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

您必须将每行读作String并解析它以获得双打:

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

答案 1 :(得分:1)

BufferReader的read()方法读取char的整数表示,而不是完整的强制转换为double或int。

要解决此问题,只需将您的for循环更改为此

即可
try
        {
            double[] savedGa = new double[4];
            BufferedReader saveFile = new BufferedReader(new FileReader("C:/test.txt"));
            for (int i = 0; i < 4; i++)
            {
                savedGa[i] = Double.parseDouble(saveFile.readLine());
            }
            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.");
        }

这将整行读取为String,然后将其解析为double。