簡體   English   中英

格式化從文本文件讀取的數據

[英]Formatting data read in from text file

我有一個對象Location,該對象接受參數字符串名稱,int xCoordinate,int yCoordinate。 我有以下文本文件,可從中讀取值並將它們轉換為Location對象。

Location: Italy 65 120
Location: Spain 20 100
Location: France 130 60
Location: England 160 140
Location: Scotland 65 100
Location: Hungary 110 120
Location: Ireland 20
120

Location: Russia 40 10
Location: America 90 15
Location: Greece 

39 23
Location: India 49 5
Location: Japan 11 20
Location: Africa 110
100

Location: Norway 22 30
Location: Sweden 34 35
Location: Iceland
94 22
Location: Denmark 36 20

請注意,位置始終以“ Location:”開頭,並且名稱和坐標可以用任意數量的行分隔。

我想出了以下代碼,但似乎無法正常工作:

FileInputStream fileIn = new FileInputStream("src\\graph.txt");
Scanner scan = new Scanner(fileIn);
WorldMap map1= new WorldMap();
while(scan.hasNext()) {
    if(scan.next().equals("Location:")) {
        map1.addLocation(scan.next(), scan.nextInt(), scan.nextInt());
    }
}

用以下代碼替換您的代碼:

while(scan.hasNextLine()) {
    if(scan.nextLine().startsWith("Location:")) {
        //doWhatver you want to Do here 
    }
}

更好的方法是讀取所有行並使用一組正則表達式確定如何處理該行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM