Problem with user inputs

Asked

Viewed 71 times

2

I have the following code:

public class FlagApplication {

    private Scanner keyboard;

    ....

    private void insertNewRegistry(){
       System.out.println("insira os dados de pessoa: nome, peso, altura, idade, sexo e bi.");

       String nome = keyboard.nextLine();
       System.out.println("nome: " +nome);
       double peso = keyboard.nextDouble();
       System.out.println("peso: " +peso);
       int altura = keyboard.nextInt();
       System.out.println(altura);
       int idade = keyboard.nextInt();
       System.out.println(idade);
       char sexo = keyboard.next(".").charAt(0);
       System.out.println(idade);
       int bi = keyboard.nextInt();
    }

    ....

}

The problem is that the first input to be assumed is soon the weight, instead of being the name, ie does System.out.println("nome: " +nome); whose name is empty ('') and waits for the weight instead of waiting first for the name

  • Is there any way to put the rest of the code? The part where Scanner.

  • I edited, I think there’s everything that’s relevant

2 answers

2


Like Patrick said, without your full code you can’t know for sure what’s going on. But you can guess!

I think you’re giving a enter where it should not, when entering the data.

I rewrote part of your code, trying to reproduce the error:

import java.util.Scanner;

class EntraDados {

    private Scanner keyboard;

    public static void main(String[] Args) {

        Scanner keyboard = new Scanner(System.in);

        System.out.println("-------");

        System.out.print("Insira seu nome: ");
        String nome = keyboard.nextLine();


        System.out.print("Agora seu peso: ");
        double peso = keyboard.nextDouble();


        System.out.print("E a sua altura: ");
        int altura = keyboard.nextInt();

        System.out.print("Insira a sua idade: ");
        int idade = keyboard.nextInt();

        System.out.print("E o seu sexo: ");
        char sexo = keyboard.next(".").charAt(0);

        System.out.println("-------");

        System.out.println("Nome: " + nome);
        System.out.println("Peso: " + peso);
        System.out.println("Altura: " + altura);
        System.out.println("Idade: " + idade);
        System.out.println("Sexo: " + sexo);

    }
} 

Execução de "EntraDados"

It seems to work! Please include your code if my suggestion does not suit you.

1

There is a possibility of errors in reading variables when using nextInt, nextDouble, nextFloat, etc... I think it is because the 'enter' character can be improperly converted to number, thus boasting the reading.

I always use next() or nextLine() and then convert the number this way:

double peso = Double.paraseDouble(keyboard.nextLine());

int altura = Integer.parseInt(keyboard.nextLine());

Browser other questions tagged

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