Java 尝试创建自动类型的数组时出错
我试图编写一个代码,读取一个文本文件,并将每一行存储到一个数组中,以下是我的代码:Java 尝试创建自动类型的数组时出错,java,arrays,java.util.scanner,Java,Arrays,Java.util.scanner,我试图编写一个代码,读取一个文本文件,并将每一行存储到一个数组中,以下是我的代码: import java.util.Scanner; import java.io.File; public class JavaPractice { public static void main (String[] args) throws Exception { File file = new File("C:/Users/Andrew/Desktop/textFile.txt"); Sca
import java.util.Scanner;
import java.io.File;
public class JavaPractice
{
public static void main (String[] args) throws Exception
{
File file = new File("C:/Users/Andrew/Desktop/textFile.txt");
Scanner fileScanner = new Scanner(file);
int x = 1;
while (fileScanner.hasNextLine())
{
fileScanner.nextLine();
x++;
}
String names[] = new String[x];
Scanner reader = new Scanner(file);
while (reader.hasNextLine())
{
names[x] = reader.nextLine();
System.out.println(names[x]);
x--;
}
System.out.println(names[0]);
fileScanner.close();
reader.close();
}
}
我要做的是让FileScaner读取我的文件有多少行,将其存储到X中,然后用X个值创建一个数组,然后开始将我的值存储到数组中。问题在于数组声明和在while循环中访问数组的方式
String names[] = new String[x];
Scanner reader = new Scanner(file);
while (reader.hasNextLine())
{
names[x] = reader.nextLine();
System.out.println(names[x]);
x--;
}
您正在声明大小为x的数组
String names[] = new String[x];
在这样访问的while循环中
names[x] = reader.nextLine();
这将运行ArrayIndexOutOfBounds异常,因为您只能访问数组中的0到x-1元素
你应该试着这样做
names[x-1] = reader.nextLine();
System.out.println(names[x-1]);
同样,你应该声明你的x=0而不是x=1;因此,您的行数正确。错误是什么?在哪一行?它在第7行显示,但这只是我的主meothod的开始,很奇怪。错误是什么?你想让这些行在数组中向后显示吗?你不能使用ArrayList吗?可能是重复的我得到了相同的错误。我刚刚将-1添加到reader.NextLine()中,得到了相同的错误,也产生了x=0,仍然是相同的错误,除了我的异常错误是:6而不是:7使用predecrement就可以了。就像我在回答中添加的一样,您应该声明x=0而不是x=1,并且不需要打印System.out.println(名称[0]);在你的while循环之后。只要做这些更正,你就会很好。在print语句中也要使用x-1,System.out.println(name[x-1]);