¿Cómo puedo ocupar el espacio [0][0] con información del usuario? Cuando se imprime, comienza en [0][1] en lugar de [0][0]
Scanner scan = new Scanner(System.in); int sizeArray; //Prompting user for number of users to be added System.out.println("How many users are you going to add?"); sizeArray = scan.nextInt(); //Reading users to add String user [][] = new String[sizeArray][2]; System.out.println("Enter name followed by unique password: "); for(int i = 0; i < sizeArray; i++) { for (int j = 0; j< 2; j++) { user[i][j] =scan.nextLine(); } } System.out.println("You entered: "); for(int i = 0; i < sizeArray; i++) { for(int j = 0; j < 2; j++) { System.out.println(" Name["+i+"]["+j+"] = "+user[i][j]); } System.out.print(""); }Cuando se imprime, comienza en [0][1] en lugar de [0][0]
está invocando el método scan.nextInt() antes scan.nextLine() que no consume el último carácter de nueva línea de la entrada del usuario, por lo tanto, el primer scan.nextLine() dentro del bucle consume ese carácter de nueva línea y cuando intenta recuperar el elemento en [0][0] dentro de la matriz bidimensional del user , imprimirá una string vacía.
una solución rápida que le permitirá imprimir los valores esperados que comienzan en [0][0] está justo después de esto:
System.out.println("Enter name followed by unique password: ");inserta esto:
scan.nextLine();ahora se convierte en:
System.out.println("Enter name followed by unique password: "); scan.nextLine(); // let this consume the newline character public static void main(String[] args) { Scanner scan = new Scanner(System.in); int sizeArray; System.out.println("How many users are you going to add?"); sizeArray = Integer.parseInt(scan.nextLine()); String user[][] = new String[sizeArray][2]; System.out.println("Enter name followed by unique password: "); for (int i = 0; i < sizeArray; i++) { String[] input = scan.nextLine().split(" "); for (int j = 0; j < 2; j++) { user[i][j] = input[j]; } } System.out.println("You entered: "); for (int i = 0; i < sizeArray; i++) { for (int j = 0; j < 2; j++) { System.out.println("Name[" + i + "][" + j + "] = " + user[i][j]); } System.out.print(""); } }¿Supongo que esta es la respuesta a tu problema? :)