Problem when using Scanner # nextLine (); inside a for

8

The question is that I want to enter a String that can contain space (ex: United States) and for that reason I use the nextLine, but also in that same method I enter data type Int. The problem is that being inside a for in the second entry, it gets fucked by the nextLine theme.

Enter country name: United States Enter the number of inhabitants: 300

And then this happens:

Enter country name: Enter the number of inhabitants:

I leave the code, I had thought of a possible solution (make the charges separately but definitely not very good to ask 2 things separately). PS: Suppose that the vector is N quantity instead of 5.

import java.util.Scanner;

public class Problema {
private Scanner teclado;
private String[] paises;
private int[] habitantes;

public void cargar() {
    teclado = new Scanner(System.in);
    paises = new String[5];
    habitantes = new int[5];
    System.out.println("Carga de paises y cant de habitantes!");

    for(int f = 0; f < paises.length; f++) {
        System.out.print("Ingrese nombre de país: ");
        paises[f] = teclado.nextLine();
        //teclado.nextLine();
        //paises[f] = teclado.nextLine();
        System.out.print("Ingrese la cantidad de habitantes: ");
        habitantes[f] = teclado.nextInt();
    }
}

public void ordenarAlfabeticamente() {
    for(int k = 0; k < paises.length-1; k++) {
        for(int f = 0; f < paises.length-1-k; f++) {
            if(paises[f].compareTo(paises[f+1]) > 0) {
                String auxpaises;
                auxpaises = paises[f];
                paises[f] = paises[f+1];
                paises[f+1] = auxpaises;
                int auxhabitantes;
                auxhabitantes = habitantes[f];
                habitantes[f] = habitantes[f+1];
                habitantes[f+1] = auxhabitantes;
            }
        }
    }
}

public void ordenarHabitantes() {
    for(int k = 0; k < habitantes.length-1; k++) {
        for(int f = 0; f < habitantes.length-1-k; f++) {
            if(habitantes[f] < habitantes[f+1]) {
                int auxhabitantes2;
                auxhabitantes2 = habitantes[f];
                habitantes[f] = habitantes[f+1];
                habitantes[f+1] = auxhabitantes2;
                String auxpaises2;
                auxpaises2 = paises[f];
                paises[f] = paises[f+1];
                paises[f+1] = auxpaises2;                   
            }
        }
    }
}

public void imprimirA() {
    System.out.println("Nombres de paises en orden alfabeto y sus habitantes: ");
    for(int f = 0; f < paises.length; f++) {
        System.out.println(paises[f] + " - " + habitantes[f]);
    }
}

public void imprimirB() {
    System.out.println("Nombres de paises y habitantes ordenado de mayor a menor: ");
    for(int f = 0; f < habitantes.length; f++) {
        System.out.println(paises[f] + " - " + habitantes[f]);
    }
}

public static void main(String[] ar) {
    Problema prob = new Problema();
    prob.cargar();
    prob.ordenarAlfabeticamente();
    prob.imprimirA();
    prob.ordenarHabitantes();
    prob.imprimirB();
}
}
    
asked by Popplar 20.01.2016 в 02:32
source

3 answers

13

The problem is that:

habitantes[f] = teclado.nextInt();

Does not remove the line change from the teclado buffer so the call to:

paises[f] = teclado.nextLine();

Find the line change as the first character and take it as an empty line

There are two ways to solve it:

Consuming line change with teclado.nextLine() after teclado.nextInt();

for(int f = 0; f < paises.length; f++) {
    System.out.print("Ingrese nombre de país: ");
    paises[f] = teclado.nextLine();
    //teclado.nextLine();
    //paises[f] = teclado.nextLine();
    System.out.print("Ingrese la cantidad de habitantes: ");
    habitantes[f] = teclado.nextInt();
    teclado.nextLine()  // Esto quitará del buffer el cambio de línea
}

Reading the number as String and then pairing it to Integer

for(int f = 0; f < paises.length; f++) {
    System.out.print("Ingrese nombre de país: ");
    paises[f] = teclado.nextLine();
    //teclado.nextLine();
    //paises[f] = teclado.nextLine();
    System.out.print("Ingrese la cantidad de habitantes: ");
    habitantes[f] = Integer.parseInt(teclado.nextLine()); //Esto extrae el número como String pero luego lo parsea como 'Integer'
}

It should be noted that in both cases it is probably better to include the reading of the number within a try catch and both will fail if a string that does not represent a number is entered.

    
answered by 20.01.2016 / 07:26
source
2

What is missing is the reading of integers since you use the same scanner, what you can do is use the same nextLine (), and transform it to whole.

Change this line

habitantes[f] = teclado.nextInt();

for this line

habitantes[f] = Integer.parseInt(teclado.nextLine());
    
answered by 20.01.2016 в 04:43
1

Well, I already solved the problem. What happened was that when entering values in the inhabitants variable you did not clean the buffer and the next field, which was text, recognized it as an invalid field. Then I leave the code and the results of the console, I hope it is helpful, you just have to sort the data to make it look more aesthetic, greetings.

package ayuda;
import java.util.Scanner;

public class Paises_habitantes {

  public static void main(String[] args) {
    Scanner c = new Scanner(System.in);

    String [] paises = new String[5];
    int [] habitantes = new int[5];

    System.out.println("carga de paises y cantidad de habitantes");

    for (int f=0;f<5;f++){
        System.out.print("Ingrese nombre del pais: ");
        paises[f]=c.nextLine();
        System.out.print("Ingrese la cantidad de haitantes: ");
        habitantes[f]=c.nextInt();
        c.nextLine(); //se utiliza para limpiar el buffer del teclado por variables int aqui estaba tu error
    }
    for(int x=0;x<5;x++){
        System.out.println("Mostrando resultados de captura: ");
        System.out.println("Pais: "+paises[x]+" Numero de habitantes: "+habitantes[x]);
    }
  }
}

Console results:

  

load of countries and number of inhabitants
  Enter name of the country: Mexico
  Enter the number of inhabitants: 80000000
  Enter name of the country: united states
  Enter the number of inhabitants: 100000000
  Enter name of the country: germany
  Enter the number of inhabitants: 60000000
  Enter country name: russia
  Enter the number of inhabitants: 50000000
  Enter country name: england
  Enter the number of inhabitants: 3000000
  Showing capture results:
  Country: mexico Number of inhabitants: 80000000
  Showing capture results:
  Country: United States Number of inhabitants: 100000000
  Showing capture results:
  Country: germany Number of inhabitants: 60000000
  Showing capture results:
  Country: Russia Number of inhabitants: 50000000
  Showing capture results:
  Country: england Number of inhabitants: 3000000

    
answered by 04.11.2016 в 18:57