01/10/2018, 00:56
Lỗi Java NullPointerException
Cho em hỏi về lỗi trong Java
![](/pictures/picfullsizes/2018/10/01/waw1538408716.png)
Đây là code của em
package SinhVien;
import java.util.Scanner;
public class SinhVien {
private String ms;
private String ten;
private Date ns;
private int soHP;
private String[] tenHP;
private String[] diemHP;
public SinhVien() {
ms = null;
ten = "unknown";
ns = new Date();
soHP = 0;
for (int i = 0; i < soHP; i++) {
tenHP[i] = "unknown";
diemHP[i] = "unknown";
}
}
public SinhVien(String ms, String ten, Date ns, int soHP, String[] tenHP, String[] diemHP) {
this.ms = ms;
this.ten = ten;
this.ns = ns;
this.soHP = soHP;
this.tenHP = tenHP;
this.diemHP = diemHP;
}
public void nhap() {
System.out.print("Nhap ma so sinh vien: ");
this.ms = new Scanner(System.in).nextLine();
System.out.print("Nhap ten sinh vien: ");
this.ten = new Scanner(System.in).nextLine();
System.out.println("Nhap ngay sinh sinh vien: ");
this.ns.nhapNgay();
System.out.print("Nhap so luong hoc phan: ");
this.soHP = new Scanner(System.in).nextInt();
for(int i = 0; i < soHP; i++) {
System.out.print("Nhap ten hoc phan thu " + (i + 1) + ": ");
this.tenHP[i] = new Scanner(System.in).nextLine();
System.out.print("Nhap diem hoc phan thu " + (i + 1) + ": ");
this.diemHP[i] = new Scanner(System.in).nextLine();
}
}
public void xuat() {
System.out.println("MSSV: " + this.ms);
System.out.println("Ten SV: " + this.ten);
System.out.println("Ngay sinh: " + this.ns.toString());
System.out.println("So luong HP: " + this.soHP);
for (int i = 0; i < soHP; i++) {
System.out.println("Ten hoc phan thu " + (i + 1) + ": " + tenHP);
System.out.println("Diem hoc phan thu " + (i + 1) + ": " + diemHP);
}
}
}
![](/pictures/picfullsizes/2018/10/01/ejn1538408716.png)
Bài liên quan
Bạn chưa khởi tạo kích thước của mảng tenHP.
Cảm ơn bạn mình đã sửa phần nhập được rồi, nhưng không hiểu sao lúc xuất ra nó như thế này.
À, bạn phải in ra phần tử, chỗ
System.out.println("Ten hoc phan thu " + (i + 1) + ": " + tenHP[i];
OK mình làm được rồi. Cảm ơn bạn nhiều nhé ^^.