Lỗi java.lang.NullPointerException với class Student

class Studen chỉ là hàm get với set e ko để ra để đỡ rối

Public class Main {
public static void outputStuden(Studen Stu) {
		System.out.println("Họ và tên: " + Stu.getStuden_Name());
		System.out.println("Mã số sinh viên: " + Stu.getStuden_code());
		System.out.println("Điểm toán: " + Stu.getMath_point());
		System.out.println("Điểm lý: " + Stu.getPhysics_point());
		System.out.println("Điểm hóa: " + Stu.getChemical_point());
	}

public static void outPullAllStuden() {
		for(int i = 0;i<Student.length;i++) {
			outputStuden(Student[i]);
		}
	}
}

Bạn tạo mảng có số phần tử cố định phải không? Các phần tử chưa được gán giá trị thì toàn bằng rỗng (null). Thế là xảy ra lỗi thôi.
Sửa đơn giản:

public static void outPullAllStuden() {
		for(int i = 0;i<Student.length;i++) {
			if(Student[i]!=null) outputStuden(Student[i]);
		}
	}
}

Làm đến thế mà vẫn chưa biết cách kiểm tra rỗng nữa à? Thao tác quan trọng đấy.

3 Likes

Thanks bạn nhiều nhiều nhiều mình fix được rồi

Xin góp ý xí:

  • Rỗng với NULL Khác nhau ạ.
  1. string str_a = null; // null
  2. string str_b = “”; // rỗng
    Tham khảo: https://stackoverflow.com/questions/5615747/what-is-the-difference-between-null-and-empty
    ==> Important:
    A variable is NULL if it has no value, and points to nowhere in memory.

empty() is more a literal meaning of empty , e.g. the string "" is empty, but is not NULL

Manythanks!

3 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?