2014-05-10 36 views
1

我對Java很新,但是這讓我在最後半個鐘頭左右難倒了。我從文本文件讀取行並將它們存儲爲字符串數組。從這裏我試圖使用數組內的值來初始化我擁有的另一個類。要初始化我的Route類(因此使用routeName),我需要從數組中獲取第一個值並將其作爲字符串傳遞。當我嘗試返回s [0]作爲routeName時,我會從我的文本文件中得到最後一行。任何想法如何解決這個將不勝感激。我正在測試過程中,所以我的代碼幾乎沒有完成。字符串數組沒有返回預期值

我的文本文件如下。

66個

UQ湖,南岸

1,2,3,4,5

2,3,4,5,6

和我的代碼:

import java.io.*; 
import java.util.*; 


public class Scan { 

    public static void main(String args[]) throws IOException { 

     String routeName = ""; 
     String stationName = " "; 
     Scanner timetable = new Scanner(new File("fileName.txt")); 
     while (timetable.hasNextLine()) { 
      String[] s = timetable.nextLine().split("\n"); 
      routeName = s[0]; 

     } 
     System.out.println(routeName); 
    } 

} 

回答

1

您撥打的方法timetable.nextLine.split(「\ n」)將返回字符串數組。 因此,每當你調用這個方法時,都會用新的文件覆蓋你的數組,最後一行最後添加到你的數組中,最後你會得到lat行。下面是您可以使用的代碼 。

public static void main(String[] args) throws FileNotFoundException { 
     String routeName = ""; 
     Scanner timetable; 
     int count = 0; 
     String[] s = new String[10]; 
     timetable = new Scanner(new File("fileName.txt")); 
     while (timetable.hasNextLine()) { 
      String line = timetable.nextLine(); 
      s[count++] = line; 
     } 
     routeName = s[0]; 
     System.out.println(routeName); 
} 
1

Scanner.nextLine()返回一條單行,所以按'\n'拆分將總是給一個單一的元素陣列,如:

timetable.nextLine().split("\n"); // e.g., "1,2,3,4,5" => ["1,2,3,4,5"] 

嘗試分裂由 ',' 代替,例如:

timetable.nextLine().split(","); // e.g., "1,2,3,4,5" => ["1", "2", "3", "4", "5"] 

注:如果您打算爲陣以包含單獨的行,然後檢查出this SO post

Scanner s = new Scanner(new File(filename)); 
List<String> lines = new ArrayList<String>(); // A List can be dynamically resized 
while(s.hasNextLine()) lines.add(s.nextLine()); // Store each line in the list 
String[] arr = lines.toArray(new String[0]); // If you really need an Array, use this 
0

while while循環遍歷所有行並將當前行設置爲routeName。這就是爲什麼你會在你的最後一行字符串。當你閱讀文件的第一行時,你可以做的就是打電話休息一下。然後你會有第一行。