5
It’s a very beginner question (I’m new to Java, I came from C++). I have to do a program that takes 4 grades from 10 students, but when I go to work with the "pointers" (arrays), my program returns an Exception:
import java.util.Scanner;
class Aluno
{
public int[] nota;
}
class Nota
{
private Aluno[] aluno;
private int totalAlunos;
private int NumeroNotas;
public Nota(int numero_alunos, int numero_notas)
{
this.totalAlunos = numero_alunos;
this.NumeroNotas = numero_notas;
this.aluno = new Aluno[numero_alunos];
for(int i = 0; i < totalAlunos; i++)
{
this.aluno = new Aluno[numero_notas];
}
for(int numero_de_alunos = 0; numero_de_alunos < numero_alunos; numero_de_alunos++)
{
System.out.print("Aluno " + (numero_de_alunos+1) + ":\n");
Scanner Scan = new Scanner(System.in);
for(int i = 0; i < NumeroNotas; i++)
{
System.out.print("Digite a nota número " + (i+1) + ": ");
this.aluno[numero_de_alunos].nota[i] = Scan.nextInt();
System.out.print("\n");
}
}
}
public int PegarMedia(int NumeroAluno)
{
int stack = 0;
for(int i = 0; i < NumeroNotas; i++)
{
stack += this.aluno[NumeroAluno].nota[i];
}
return stack / NumeroNotas;
}
public void MostrarMedia()
{
for(int i = 0; i < totalAlunos; i++)
{
System.out.print("Media do aluno " + i + ":");
System.out.print(PegarMedia(i) + "\n");
}
System.out.print("\n");
}
}
//Fim das classes
class Test
{
public static void main(String args[])
{
Nota notas = new Nota(10,4);
notas.MostrarMedia();
}
}
Return:
run: Student 1: Exception in thread "main" java.lang.Nullpointerexception Type note number 1: at Note.(Test.java:28) at Test.main(Test.java:59) Java Result: 1
What am I doing wrong? What should I do?
Thanks :) I made a mistake, I did the opposite. But now, after putting all the numbers, I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
 at Nota.<init>(Test.java:28)
 at Test.main(Test.java:59)
Java Result: 1
. And in ideone, it gives others: https://ideone.com/mrilal– user2692
I updated the answer, check it out.
– Piovezan