简体   繁体   English

如何将用户值添加到2D数组中

[英]How do I add user values into a 2D array

Given the 2d array: 给定2d数组:

double[][] table;
table = new double[4][5];

I know how to print the array with 20 0's using: 我知道如何使用20 0打印数组:

for (int ii = 0 ; ii < table.length ; ii++)
{
    for (int jj = 0 ; jj < table[0].length ; jj++)
    {
      System.out.print(table[ii][jj] + "\t");
    }
  System.out.println("");
}

I would like to ask the user to input "1,2,3" where 1 is the row, 2 is the column and 3 is the value that goes in the cell. 我想请用户输入“ 1,2,3”,其中1是行,2是列,3是单元格中的值。 Please help me how to do this using the string split method. 请帮助我如何使用字符串拆分方法执行此操作。 Thank you! 谢谢!

That's easy if you go step by step: 如果您一步一步走,那很容易:

  • use Scanner class on System.in to read a line through nextLine() 使用System.in上的Scanner类通过nextLine()读取一行
  • split the String according to the given delimiter ( "," ) 根据给定的分隔符( "," )分割String
  • check if amount of tokens is correct 检查令牌数量是否正确
  • convert each token to an int through Integer.parseInt(..) 通过Integer.parseInt(..)将每个令牌转换为一个int
  • set the correct value through table[x][y] = v 通过table[x][y] = v设置正确的值
String numString = "1,2,3";

String[] splitString = numString.split(",");

int num1 = Integer.parseInt(splitString[0]);
int num2 = Integer.parseInt(splitString[1]);
int num3 = Integer.parseInt(splitString[3]); 

table = new double[4][5];
table[num1][num2] = num3;

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

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