Remember that since everything is private, the class that inherits this will not have access to these members. You may want to switch to protected
.
Add this to class Aluno
:
private int totalCursos = 0;
public void addCurso(String curso) {
if (totalCursos == 5) {
throw Exception("Quantidade de cursos chegou ao limite");
}
cursos[totalCursos] = curso;
totalCursos++;
}
If you want to add multiple
public void addCursos(String ... listaCursos) {
if (totalCursos > 5 - cursos.Length) {
throw Exception("Quantidade de cursos chegou ao limite");
}
for(String curso : listaCursos){
cursos[totalCursos ] = curso;
totalCursos++;
}
}
Of course you can do it differently. But that's the idea. If it were more than an exercise, other care would probably need to be taken. If you could do otherwise than the specified requirement, you would do better. Launch Exception
is not correct in normal code, but creating a new exception just for this in a simple exercise is overkill. I would even do it without exception, but this is not Java culture. So:
public Boolean addCurso(String curso) {
if (totalCursos == 5) {
return false;
}
cursos[totalCursos] = curso;
totalCursos++;
return true;
}
Note that I preferred to use a name starting with add
to reflect what you're adding. If you prefer, change to adiciona
.
To list:
public void listCursos() {
for(String curso : cursos) {
System.out.println(curso);
}
}
Modify:
public boolean changeCurso(String cursoModificar, String cursoNovo) {
for(String curso : cursos) {
if (curso.equals(cursoModificar)) {
curso = cursoNovo;
return true;
}
}
return false;
}
Another direct version by the position of the course in the cadastre:
public boolean changeCurso(int cursoModificar, String cursoNovo) {
if (cursoModificar < 0 || cursoModificar > totalCursos - 1) {
return false;
}
cursos[cursoModificar] = cursoNovo;
return true;
}
Remove:
public boolean removeUltimoCurso() {
if (totalCursos == 0) {
return false;
}
cursos[totalCursos - 1] = null;
totalCursos--;
return true;
}
public boolean removeTodosCursos() {
cursos = new String[5];
return true;
}
You can do the removal by position and search, just as you did in the modification, but there you need to set a array cleanup criterion, which, although relatively simple, is not so trivial to anyone who is starting.