Create more than one variable using the scanner command

Asked

Viewed 252 times

0

I did a search by google but could not get an answer that illuminated my head, I’m starting to study java and I came across the following problem:

Create a Java program that reads from the keyboard 10 names and their salaries and then show the name of who has the highest and lowest salary.

Remembering that I still haven’t done the if part at the end to compare, my own doubt is how to save different variables using the scanner.

From now on Obriagdo:

public static void main(String[] args) {

    String nome1;
    int salario1;
    int contador = 0;


    while (contador <= 15) {
        System.out.println(" Qual o seu nome?");
        Scanner nome = new Scanner(System.in);
        nome1 = nome.next();
        System.out.println(" Qual o seu salário?");
        Scanner salario = new Scanner(System.in);
        salario1 = salario.nextInt();


        contador = (contador + 1);

    }
}
  • Recommended reading https://answall.com/questions/209571/erro-nosuchelementexception-ao-capturr-dataentrada-com-scanner/209580#209580

1 answer

0


Scanner returns a String value, if you want to save multiple values you can use an Arraylist to save all names and another to save wages more if you want to do the way you did can do so:

    public static void main(String[] args) {

    String nome;
    int salario;
    int contador = 0;
    Scanner s = new Scanner(System.in);
    String nomeMaior = null;
    String nomeMenor = null;
    int salarioMaior = 0;
    int salarioMenor = 0;

    while (contador < 10) {
        System.out.println("Qual seu nome? ");
        nome = s.next();
        //System.out.println(nome);
        System.out.println("Qual seu salário? ");
        salario = Integer.parseInt(s.next());
        //System.out.println(salario);

                    // vc tem que testa toda vez que pedir um nome e salario novo
                    // enquanto tiver mais de um nome                        

        if (contador > 0) {
            if (salario > salarioMaior) {
                nomeMaior = nome;
                salarioMaior = salario;
            } else if (salario < salarioMenor) {
                nomeMenor = nome;
                salarioMenor = salario;
            }
        } else {
            nomeMaior = nome;
            nomeMenor = nome;
            salarioMaior = salario;
            salarioMenor = salario;
        }

        contador+=1;
    }
    System.out.println("Maior : " + nomeMaior + " " + salarioMaior);
    System.out.println("Menor : " + nomeMenor + " " + salarioMenor);
}
  • Thank you very much, I had this idea in my head, but I was not able to write. Thank you!

Browser other questions tagged

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