使用扫描仪读取城市名称

时间:2014-01-23 04:34:49

标签: 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 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();
    }

这是输出

Loaded 4 cities: 
    has location id 0
    New York has location id -1
    Los Angeles has location id 2
    Chicago has location id -1

1 个答案:

答案 0 :(得分:1)

我认为in.nextInt()不会自动转到下一行。所以你正在读第一行的其余部分为空白。

尝试用in.nextLine()

替换in.reset()