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();
}
}