[英]Why am I getting null pointer exception in this program when using enhanced for loop
我在selectAllStudent方法中得到一個空指針異常。 當我使用foreach循環但當我使用普通循環時,它工作正常。 請說明原因。 謝謝
駕駛員等級
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) {
Student[] sdb = new Student[2];
try {
for (Student s : sdb) {
s = takeInput();
}
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
selectAllStudent(sdb);
}
static void selectAllStudent(Student[] sdb) {
for (Student s : sdb) {
s.printStudentDetails(); // Getting NullPOinterException here
}
}
public static Student takeInput() throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the details ");
System.out.print("ROLL :"); int rollno = Integer.parseInt(in.readLine());
System.out.print("NAME :"); String name = in.readLine();
System.out.print("BRANCH :"); String branch = in.readLine();
return (new Student(rollno,name,branch));
}
}
學生班
public class Student {
private int rollno;
private String name;
private String branch;
Student(int rollno, String name, String branch) {
this.rollno = rollno;
this.name = name;
this.branch = branch;
}
void printStudentDetails() {
System.out.println("ROLLNO :" + rollno);
System.out.println("NAME :" + name);
System.out.println("BRANCH :" + branch);
System.out.println("-------------------");
}
}
您沒有在此for
循環中為該數組分配新的Student
。
for (Student s : sdb) {
s = takeInput();
}
takeInput
方法可以正確返回Student
,但是您已將其分配給本地引用s
,而不是數組sdb
的元素。 數組的元素保持為null
,並且NullPointerException
來自嘗試在selectAllStudent
方法中的null
上調用printStudentDetails
。
您可以將增強型for
循環轉換for
標准for
循環,為Student
分配數組訪問表達式。
for (int i = 0; i < sdb.length; i++)
{
sdb[i] = takeInput();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.