I don’t understand why it doesn’t work

Asked

Viewed 83 times

2

I have a problem here, I don’t know why it doesn’t print anything. There are no compilation errors, but it doesn’t work.

Class Students

import java.io.PrintStream;

public class Alunos {
    private String primeiro;
    private String segundo;
    private int idade;
    private static int quantidade;

    Alunos(String pn,String sn,int i){
        primeiro=pn;
        segundo=sn;
        idade=i;
        quantidade++;
        System.out.printf("Aluno %s %s juntou-se a turma, ele tem %d anos!A turma tem agora %d alunos. \n",primeiro , segundo, idade,quantidade);
    }

    
}

Test Class

import java.util.Random;
import java.util.Scanner;
import java.util.EnumSet;

public class Teste {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String pn;
        String sn;
        int idade = 0;

        for (int contador = 0; contador < 5; contador++) {
            System.out.println("Insira o primeiro nome, segundo nome e idade:");
            pn = sc.nextLine();
            sn = sc.nextLine();
            idade = sc.nextInt();
            Alunos Aluno = new Alunos(pn, sn, idade);
        }

    }

}
  • Here in my test printed normally, after asking for the parameters via keyboard: "Student Murillo Goulart joined the class, he is 28 years old! The class now has 1 students. "

  • yes but if you do again will give an error , if continue the cycle is

  • 1

    The reason for the error and how to resolve it is explained in the answers to this linked question.

2 answers

4

In your for code, do the instantiation of Scanner again:

    for (int contador = 0; contador < 5; contador++) {
        System.out.println("Insira o primeiro nome, segundo nome e idade:");
        Scanner sc = new Scanner(System.in);
        pn = sc.nextLine();
        sn = sc.nextLine();
        idade = sc.nextInt();
        Alunos Aluno = new Alunos(pn, sn, idade);
    }

ps. There are other practices that are not being followed, but I will not prolong the question.

1

You need to assign an initial value to the variable "quantity" in the Students class

private static int quantidade = 0;

Hug

  • This variable is initialized implicitly. So that’s not the problem.

Browser other questions tagged

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