I'm new in the community and I need help with Array 2d in Java Is a project for school this is my problem
I build Array 2D with static length and work but the same code with parameters not work.
First print the System.out.print("Insert Name");
after that not execute the statement matrix[i][0] = input.nextLine();
third print System.out.print("Insert Last Name");
now works but the index [0],[0] is empty
Example of print:
a
bb
cc
Thanks!!!
import java.util.*;
public class Students {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Insert number of Students");
int numStudents = input.nextInt();
String[][] matrix = new String[numStudents][2];
for (int i = 0; i < numStudents; i++) {
System.out.print("Insert Name");
matrix[i][0] = input.nextLine();
for (int j = 1; j < 2; j++) {
System.out.print("Insert Last Name");
matrix[i][j] = input.nextLine();
}
}
for(int z=0; z<numStudents ;z++) {
System.out.println();
for(int h=0; h<2;h++) {
System.out.printf(matrix[z][h]);
System.out.printf(" ");
}
}
}
}
Use String value= input.next(); instead of input.nextLine(); or use an extra input.nextLine(); after input.nextInt(); ie
int numStudents = input.nextInt();
input.nextLine()
This happens because input.nextInt() just reads one integer and does not finishes the line.
I think this should work for you. No need of a nested for loop to read last name.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Insert number of Students");
int numStudents = input.nextInt();
input.nextLine();
String[][] matrix = new String[numStudents][2];
for (int i = 0; i < numStudents; i++) {
System.out.println("Insert Name");
matrix[i][0] = input.nextLine();
System.out.println("Insert Last Name");
matrix[i][1] = input.nextLine();
}
for (int z = 0; z < numStudents; z++) {
System.out.println();
for (int h = 0; h < 2; h++) {
System.out.print(matrix[z][h]);
System.out.print(" ");
}
System.out.println();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.