The code is right but could do better:
class Aluno {
String nome;
int idade;
public Aluno(String nome, int idade) {
this.nome = nome;
this.idade = idade;
}
public Aluno() { }
}
class Principal {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
Aluno aluno = new Aluno();
System.out.println("Qual tu nome");
aluno.nome = entrada.nextLine();
System.out.println("Qual tu idade");
aluno.idade = entrada.nextInt();
System.out.println("Nome: " + aluno.nome + "\nIdade: " + aluno.idade);
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
I could ask if I should have the constructor without parameters. In real code, it might not be a good idea, it is not ideal to create an object in an invalid state. But in an exercise it is no problem, even more than the solution being given was to create an object with invalid state "by force".
If you didn’t have the constructor with parameters, then you wouldn’t need any constructor, after all, when you don’t have constructors, Java creates a default without parameters that doesn’t perform initializations.
See more about builders.
I didn’t understand the doubt, you must [Dit] the question and put more relevant information so we can help you. Maybe improve the example of what you want or just explain better what you need.
– Maniero
Ali no em aluno pedro = new Aluno(); I need to pass the data obligatorily, in the example that I had seen it set in the main class scanner. how can I do?
– pedro
You can tell if this is correct http://pastebin.com/XpEh0Qb0
– pedro
Pedro, when asked to take a question here in the comments, you should [Edit] to the question, it’s not trouble, it’s important. Thank you!
– brasofilo