Java 从数组中获取null作为输出
我试图将数据从文件放到数组中。我总是得到一个空值作为输出。我不明白为什么。这是非常紧张的Java 从数组中获取null作为输出,java,Java,我试图将数据从文件放到数组中。我总是得到一个空值作为输出。我不明白为什么。这是非常紧张的 在用元素填充数组之前,正在打印该数组 在while循环的每次迭代中,计数器i都会重置为0。虽然使用具有固定数量元素的数组来读取未知长度的文本不是一个好主意,但请使用一些动态数组,如ArrayList 确保为.txt文件提供了正确的路径 因此,您的代码可以如下所示: import java.util.*; public class a{ public static void main(String[]
while
循环的每次迭代中,计数器i
都会重置为0
。虽然使用具有固定数量元素的数组来读取未知长度的文本不是一个好主意,但请使用一些动态数组,如ArrayList
.txt
文件提供了正确的路径import java.util.*;
public class a{
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File ("master file.txt"));
String[] ids = new String[100];
System.out.println(ids);
while(sc.hasNext()) {
int i = 0;
ids[i] = sc.next();
i++;
}
Scanner sc=新扫描仪(新文件(“C:/correct/path/to/File/master_File.txt”);
List listofstring=new ArrayList();
while(sc.hasNextLine()){
添加(sc.nextLine());
}
System.out.println(listOfStrings);
输出为空,因为您在尝试打印数组之前从未为数组分配任何内容。我还将I移到了循环之外,这样就不会每次都重新初始化它。此外,由于id是一个数组,因此需要使用Arrays.toString(ids)打印它,或者只获取对象id
Scanner sc = new Scanner(new File ("C:/correct/path/to/file/master_file.txt"));
List<String> listOfStrings = new ArrayList<String>();
while(sc.hasNextLine()) {
listOfStrings.add(sc.nextLine());
}
System.out.println(listOfStrings);
在
while
循环之前,将i
的初始化移动到0
。此代码的输出不可能为null。它只打印ids
,它被初始化为一个新的字符串数组。
public static void main(String[] args) throws FileNotFoundException {
String[] ids = new String[100]; //array to store lines
int i = 0; // line index
try (Scanner sc = new Scanner(new File ("master file.txt"))) { // try resource
while(sc.hasNextLine()) { // check for next line
ids[i] = sc.nextLine(); // store line to array index
i++; // increment index
}
}
System.out.println(Arrays.toString(ids)); //print output.
}