KileMax :
I want to create a 2D String array which stores name and address which are given as keyboard inputs. eg: name 1 address 1; name 2 address 2;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[][] array = new String[3][2];
for (int i = 0; i < 3; i++)
{
for(int j = 0; j < 2; j++)
{
array[i][j] = sc.nextLine();
}
System.out.println(array[0][0]);
}
}
in here I want to print a statement asking to enter the name eg. System.out.println("Enter name:"); after that I want to write another statement asking to enter the address eg.System.out.println("Enter the address"); but i cant figure out how do that in a 2d array
greenlamponatable :
How about something like this?
public static void main(String[] args) {
int rows = 3;
int cols = 2;
Scanner sc = new Scanner(System.in);
String[][] array = new String[rows][cols];
for (int row = 0; row < rows; row++) {
System.out.println("Enter name:");
array[row][0] = sc.nextLine();
System.out.println("Enter the address:");
array[row][1] = sc.nextLine();
}
// Print out array
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
System.out.print(array[row][col] + ", ");
}
System.out.print(";");
}
}
Output:
Person 1, Address 1, ; Person 2, Address 2, ; Person 3, Address 3, ;
Check it live here: https://onlinegdb.com/Byu4wc1vI
I hope this helps!
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=366553&siteId=1