我是編碼新手,我想知道如何將文本檔案的行添加到程式中的陣列中。我的代碼如下所示:
import java.io.*;
public class Test {
static String [] name = new String [3];
static String [] surname = new String [3];
public static void main(String[] args) {
try{
BufferedReader reader =null;
String currentLine = reader.readLine();
reader=new BufferedReader(new FileReader("Names.txt"));
int x=0;
while(currentLine!=null){
name[x]=reader.readLine();
currentLine=reader.readLine();
surname[x]=reader.readLine();
currentLine=reader.readLine();
x=x 1;
}
}
catch(Exception e){
System.out.println("The following error occured:" e.getMessage());
}
for(int x =0; x<name.length; x ){
System.out.println(
"name:" name[x] "\n"
"surname: " surname[x] "\n"
);
}
}
我得到的錯誤是Cannot invoke "java.io.BufferedReader.readLine()" because "reader" is null。我該如何解決?
uj5u.com熱心網友回復:
- BufferedReader 物件為空并且您正在嘗試訪問在 java 中無法訪問的物件。
- 我不明白你到底想做什么,但你可以做這樣的事情。
public class Task3 {
static String [] name = new String [3];
static String [] surname = new String [3];
public static void main(String[] args) {
try{
BufferedReader reader =null;
reader=new BufferedReader(new FileReader("/home/ancubate/names.txt"));
List<String> lines = reader.lines().collect(Collectors.toList());
int x=0;
while(lines.size() != (x 1)){
name[x]=lines.get(x);
surname[x]=lines.get(x);
x=x 1;
}
}
catch(Exception e){
System.out.println("The following error occured:" e.getMessage());
}
for(int x =0; x<name.length; x ){
System.out.println(
"name:" name[x] "\n"
"surname: " surname[x] "\n"
);
}
}
}
- reader.lines() - 從檔案中獲取所有行
- collect(Collectors.toList()) - 流 API 收集為串列
uj5u.com熱心網友回復:
我不確定我的答案。我認為是因為您忘記將java io包匯入程式。希望你明白了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/370116.html
