Program that receives a series of notes needs to disregard an invalid entry

Asked

Viewed 33 times

0

Make a program that receives a series of student grades and then print them out. However, the program cannot accept notes greater than 100 or less than 0. If the user types a wrong note, they should be able to type again.

The code so far is like this:

public class notaMenorCem
{
  public static void main (String[]args)
  {
    int notaAluno [] = new int[5];
    for (int i=0; i<notaAluno.length; i++)
    {
      notaAluno[i] = Entrada.leiaInt ("Digite a nota: ");
      {
        if(notaAluno[i] <0 || notaAluno[i] >100)
        {
          System.out.println("Nota inválida, digite novamente:");
        }
      }
    }
    for (int i=0; i<notaAluno.length; i++)
    {
      System.out.println("Nota do aluno " +i+ ":"+notaAluno[i]);
    }
  }
}

The user receives the notice by entering a note greater than 100 but it is registered equal, what is missing?

1 answer

1


Missed not doing the assignment if the validation fails, so I put a continue. And missed to turn the counter back if the item is not inserted, to keep the timing.

Missed validate when a entered value is not a number, if you do this test the application will break, but I will not fix it.

Other less relevant things were missing.

import java.util.Scanner;

public class Main {
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        int notaAluno [] = new int[5];
        for (int i = 0; i < notaAluno.length; i++) {
            var nota = sc.nextInt();;
            if (nota < 0 || nota > 100) {
                System.out.println("Nota inválida, digite novamente:");
                i--;
                continue;
            }
            notaAluno[i] = nota;
        }
        for (int i = 0; i < notaAluno.length; i++) System.out.println("Nota do aluno " + i + ":" + notaAluno[i]);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.