Java 如何从文件中读取信息并将其放回字符串数组中?
我有一项任务,需要从文件中读取信息。文件中的信息格式为: 伦敦 莫斯科 .... 我一共有7个城市和7排。我需要读取城市名称并将它们放回字符串数组中。当我测试这段代码时,我得到一条消息 java.lang.ArrayIndexOutOfBoundsException:0 我将感谢任何关于如何解决这个问题的想法Java 如何从文件中读取信息并将其放回字符串数组中?,java,Java,我有一项任务,需要从文件中读取信息。文件中的信息格式为: 伦敦 莫斯科 .... 我一共有7个城市和7排。我需要读取城市名称并将它们放回字符串数组中。当我测试这段代码时,我得到一条消息 java.lang.ArrayIndexOutOfBoundsException:0 我将感谢任何关于如何解决这个问题的想法 import java.util.Scanner; import java.io.*; public class Input { static Scanner keybo
import java.util.Scanner;
import java.io.*;
public class Input {
static Scanner keyboard, input;
static PrintWriter output;
static String[] namesCities;
static String name = "";
static int index;
public static void main(String args[]) {
try
{
System.out.println("Please, enter the name of input file");
keyboard = new Scanner(System.in);
name = keyboard.nextLine();
File file = new File(name);
input = new Scanner(file);
namesCities = new String[index];
for (int index = 0; index < 7; index++)
{
namesCities[index] = input.next();
}
}
catch
{
catch (IOException a)
{
System.out.println("Could not find file " + name);
name = keyboard.nextLine();
}
}
}
在您现有的代码中,您没有正确初始化索引变量,因为它的值保持为零,并且您的namesCities=newstring[index];结果为零大小数组,从而导致ArrayIndexOutOfBoundsException。您需要将其初始化为7,如namesCities=newstring[7] 避免在类级别声明其作用域不应超过所需时间的变量。就像代码中的扫描对象或文件名一样,它们似乎没有任何价值。事实上,如果管理不当,它们可能会导致资源泄漏。请尝试以下代码,该代码在一行中使用Files.readAllLines读取您的文件,并作为列表对象返回,其中列表中的每个项都包含您在文件中的行。然后可以使用toArray将其转换为数组
如果您理解这里的任何代码都有困难,请告诉我。因此我写了一些小东西。这假设您已经完成了所有正确的导入,并且没有实际检查以确保文件大小正确。如果您绝对必须使用for循环,您可以将我的循环更改为for循环,告诉计数器<7 not counter不要使用for循环,请使用while循环并检查扫描仪上的HASEXT。您的代码无法编译,因为初始化数组时未声明索引?请发布编译的代码。你的代码似乎有编译时错误。嗨,安娜,欢迎来到这个网站!简单提示一下:在代码中包括行号,以及接收到的整个或至少顶部异常块,通常非常有用。这样,我们可以准确地看到是哪一行导致了它,并帮助您更快地完成:您可以显示文件内容的示例吗?不用编写太多代码,您可以使用Files.readAllLinesPaths.getname以列表的形式读取所有行,这样您就不必定义数组的大小,并且可以避免ArrayIndexOutOfBoundsException@AnnaWood:后退一步,浏览代码。使用新字符串[index]初始化数组名称。这意味着您实际上是在创建一个空数组,因为索引为0。现在,您正尝试循环它,然后尝试访问一个显然不存在的索引,例如:namesCities[0]、namesCities[1]。。。因此,ArrayIndexOutofBoundsCeptionit就是一个很好的解释!我只需要改变我初始化数组的方式,它就可以工作了!
public static void main(String[] args) throws Exception {
System.out.println("Please, enter the name of input file");
Scanner keyboard = new Scanner(System.in);
String name = keyboard.nextLine();
keyboard.close();
List<String> lines = Files.readAllLines(Paths.get(name));
String[] nameCities = lines.toArray(new String[lines.size()]);
System.out.println(Arrays.toString(nameCities));
}
public class Input{
public static void main(String[] args){
System.out.println("Please Enter the name of the input file");
keyboard = new Scanner(System.in);
name = keyboard.next();
File file = new File(name);
input = new Scanner(file);
String[] nameCities = new String[7];
int counter = 0;
while(input.hasNext()){
nameCities[counter] = input.next();
counter++;
}
keyboard.close()//don't forget to close your scanner
}
}