2
I want to create a program that reads the name and age of a person and compares the ages and finally shows the name of the older person. My reasoning was to compare which is the highest and return the index of the position of the array. But the return is always 0. And also I do not know how to pick up the return and shows the content of array in position.
package Lista1;
import java.util.Scanner;
public class Pessoa {
private static String nome;
private static int idade;
public static int comparaIdade(Pessoa[] pessoa){
int maior=0;
int ind = 0;
for(int i = 0; i<3; i++){
if(pessoa[i].idade>maior){
maior=pessoa[i].idade;
ind=i;
}
}
return ind;
}
public static void main(String[] args){
Pessoa[] pessoa = new Pessoa[3];
Scanner input = new Scanner(System.in);
for(int i = 0; i<3; i++){
System.out.println("Digite o nome da pessoa: ");
pessoa[i].nome = input.nextLine();
System.out.println("Digite a idade da pessoa: ");
pessoa[i].idade = input.nextInt();
input.nextLine();
}
System.out.printf("Nome da pessoa mais velha: %d", comparaIdade(pessoa));
}
}
Is always returning the last position of the array.
– Diego Soares
It’s what I said, your code has other mistakes, it’s not just what I showed in the answer. You’re not creating 3 names, you’re creating 1 and superimposing it, so you’re always the last.
– Maniero
Fixed the main bugs.
– Maniero