Java 使用扫描仪读取城市名称

Java 使用扫描仪读取城市名称,java,arrays,file-io,Java,Arrays,File Io,我正试图让扫描仪读取一个文件。但是,问题是扫描仪一直跳过数组中的0位置。下面是代码和输出 public void loadLocations(String fname) throws Exception { Scanner in = new Scanner(new File(fname)); Locations = new String[in.nextInt()]; in.reset(); //writes lines to a

我正试图让扫描仪读取一个文件。但是,问题是扫描仪一直跳过数组中的0位置。下面是代码和输出

public void loadLocations(String fname) throws Exception {

        Scanner in = new Scanner(new File(fname));
        Locations = new String[in.nextInt()]; 
        in.reset();
        //writes lines to array.
        for (int i = 0; i < Locations.length; i++){     
            if (in.hasNextLine()){
                Locations[i] = in.nextLine();
            }

            else if (in.hasNext()) {
                Locations[i] = in.nextLine();

            }

        }   

        // close file
        in.close();
    }
我认为in.nextInt()不会自动转到下一行。因此,您将第一行的其余部分视为空白


尝试用in.nextLine()替换in.reset()

我建议您遵循Java命名约定<代码>位置,因为它是一个变量,应该命名为
位置
。尝试编写一个uni测试或使用IDE调试。您可以与我们共享该文件吗?可能是一些记录。城市文本文件或实际的程序文本文件就是它。谢谢我已经搞乱了这像3个小时lol
Loaded 4 cities: 
    has location id 0
    New York has location id -1
    Los Angeles has location id 2
    Chicago has location id -1