Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java读取文本文件(字符串和整数)_Java_Arrays_While Loop - Fatal编程技术网

Java读取文本文件(字符串和整数)

Java读取文本文件(字符串和整数),java,arrays,while-loop,Java,Arrays,While Loop,我有一种方法,尝试从文本文件读入,然后将其中的内容添加到我的数组中,我的方法似乎还可以,但当我运行程序时,屏幕上会出现空值 请帮忙这是我的密码 File text = new File("C:\\Users\\Stephen\\Desktop\\CA2\\src\\Management_System_Package\\GAMES.txt"); Scanner scnr = new Scanner(text); String GameLine; GameLine

我有一种方法,尝试从文本文件读入,然后将其中的内容添加到我的数组中,我的方法似乎还可以,但当我运行程序时,屏幕上会出现空值 请帮忙这是我的密码

    File text = new File("C:\\Users\\Stephen\\Desktop\\CA2\\src\\Management_System_Package\\GAMES.txt");
    Scanner scnr = new Scanner(text);

    String GameLine;
    GameLine = scnr.nextLine();

    while (scnr.hasNextLine()) {

        Management_System Game = new Management_System("", "", 0, 0, 0);

        int Comma1 = GameLine.indexOf(", ");
        String Title = GameLine.substring(0, Comma1).trim();
        Game.setTitle(Title);

        System.out.print(Title);

        int Comma2 = GameLine.indexOf(", ", Comma1 + 1 );
        String Genre = GameLine.substring(Comma1 + 1, Comma2);
        Game.setGenre(Genre);

        int Comma3 = GameLine.indexOf(", ", Comma2 + 1 );
        String ID = GameLine.substring(Comma2 + 1, Comma3);
        Game.setID(Double.parseDouble(ID));

        int Comma4 = GameLine.indexOf(", ", Comma3 + 1 );
        String Rating = GameLine.substring(Comma3 + 1, Comma4);
        Game.setRating(Integer.parseInt(Rating));

        String Quantity = GameLine.substring(Comma4 + 1).trim();
        Game.setQuantity(Integer.parseInt(Quantity));

        add(Game);

        GameLine = in.nextLine(); 

这是因为您的代码有一个bug,您从循环中读取一行,并且总是跳过文件的最后一行。如果文件只有一行,
scnr.hasNextLine()
将为
false
,并且不会运行while循环

我认为
split()
是获得所需字符串和整数的更好方法。代码如下:

String GameLine;

while (scnr.hasNextLine()) {
    GameLine = scnr.nextLine();
    Management_System Game = new Management_System("", "", 0, 0, 0);
    String[] tags = GameLine.split(",");

    Game.setTitle(tags[0]);

    Game.setGenre(tags[1]);

    Game.setID(Double.parseDouble(tags[2]));

    Game.setRating(Integer.parseInt(tags[3]));

    Game.setQuantity(Integer.parseInt(tags[4]));

    add(Game);
}

这就是我试图从文本文件中读到的内容:刺客Cread,Action,1.0,4,5-1@StephenJpH很高兴提供帮助:)我建议您使用
split()
而不是
indexOf()