简体   繁体   English

java - 如何将2个键盘输入带到java中的二维数组?

[英]How to take 2 key board inputs to a 2 dimensional array in java?

I want to create a 2D String array which stores name and address which are given as keyboard inputs.我想创建一个二维字符串数组,它存储作为键盘输入给出的名称和地址。 eg: name 1 address 1;例如:姓名 1 地址 1; name 2 address 2;姓名 2 地址 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:"); System.out.println("请输入姓名:"); after that I want to write another statement asking to enter the address eg.System.out.println("Enter the address");之后我想写另一个要求输入地址的语句 eg.System.out.println("Enter the address"); but i cant figure out how do that in a 2d array但我不知道如何在二维数组中做到这一点

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在这里查看: https : //onlinegdb.com/Byu4wc1vI

I hope this helps!我希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM