gpt4 book ai didi

java - 字符串数组未返回预期值

转载 作者:行者123 更新时间:2023-11-30 03:54:32 25 4
gpt4 key购买 nike

我对 Java 很陌生,但这让我在过去的半个小时左右的时间里陷入困境。我正在从文本文件中逐行读取并将它们存储为字符串数组。从这里我尝试使用数组中的值来初始化我拥有的另一个类。要初始化我的 Route 类(因此使用 RouteName),我需要从数组中获取第一个值并将其作为字符串传递。当我尝试返回 RouteName 的 s[0] 时,我得到了文本文件中的最后一行。任何有关如何解决此问题的想法将不胜感激。我仍在测试过程中,这就是为什么我的代码才刚刚完成。

我的文本文件如下。

66

昆士兰大学湖区,南岸

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

}

最佳答案

您调用的方法timetable.nextLine.split("\n")将返回字符串数组。因此,每次调用此方法时,都会用文件中的新行覆盖数组,并且当最后一行最终添加到数组中时,您将在末尾获得纬度线。以下是您可以使用的代码。

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

关于java - 字符串数组未返回预期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23578657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com