我對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);
}
}