Problem with user inputs

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 the weight, rather than the name, that is, it does System.out.println("nome: " +nome); and the name is empty ('') and waits for the weight instead of stay first waiting for the name

    
asked by anonymous 18.10.2015 / 12:30

2 answers

2

As Patrick said, without your complete code, you can not really know what's going on. But we can kick it!

I think you're giving enter where it should not, when entering data.

I rewrote some 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);

    }
} 

Executionof"EntraDados"

It seems to work! Please include your code if my suggestion is not for you.

    
19.10.2015 / 09:08
1

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

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

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

int altura = Integer.parseInt(keyboard.nextLine());
    
19.10.2015 / 14:09