简体   繁体   English

Java中的Split()方法用于多维数组

[英]Split() method in Java for multi-dimensional array

I have a two dimensional array. 我有一个二维数组。 The assignment is to accept row and columns numbers from user and if user wants to enter numeric data row by row (or column by column) he has to do that with comma. 赋值是接受来自用户的行号和列号,如果用户想要逐行(或逐列)输入数字数据,则必须使用逗号进行操作。 Such as, 3x3 will be: 例如,3x3将是:

1,2,4 1,2,4

2,5,3 2,5,3

5,3,2 5,3,2

So the the first row elements will be [0,0]=1 [0,1]=2 [0,2]=3, second row [1,0]=2 [1,1]=5 [1,2]=3, etc. I understand I should possibly do that with string, then split it for ", " and then convert it no Integer, but I have no idea how to do split in such case. 所以第一行元素将是[0,0] = 1 [0,1] = 2 [0,2] = 3,第二行[1,0] = 2 [1,1] = 5 [1,2 ] = 3,等我知道我应该用字符串做,然后将其拆分为“,”然后将其转换为没有整数,但我不知道如何在这种情况下进行拆分。

This is what I have for rows input: 这是我输入的行:

for (int row=0; row<board.length; row++){
        for (int column=0; column<board[row].length; column++){
            //System.out.print("["+board[row]+"]["+board[column]+"]: ");
            board[row][column] = myInput.nextInt(); 
            //input validation
            while ((1 > (board[row][column])) || ((board[row][column]) > board.length))
            {
                System.out.println("Please enter number between 1 to "+ board.length +":");
                board[row][column] = myInput.nextInt();
            }
        }
     }  

I think this is what you want, assuming inputStr stores the user input: 我认为这是你想要的,假设inputStr存储用户输入:

String[] values = inputStr.split(',');
if(values.length != 2) {
   //Tell them they should enter two numbers
   System.out.println("Please enter two numbers separated by a comma");
}
else {
   try {
      int rowVal = Integer.parseInt(values[0]);
      int columnVal = Integer.parseInt(values[0]);

      System.out.println("The value is: "+board[rowVal][columnVal]);
   }
   catch (NumberFormatException e) {
      //It was comma separated but not two numbers
      System.out.println("Please enter two numbers separated by a comma");
   }
}

For row by row insertion: 对于逐行插入:

//Just to clean up the code
int rows = board.length;
int columns = board[0].lemgth;

String[][] dataValues = new String[rows][columns]
String[] data = new String[rows.length];
//Recieve data
for(int i = 0; i < rows; i++) {
   data[i] = input.nextString();  //modify with however you get a String in.
}
//Parse numbers
for(int i = 0; i < rows; i++) {
   dataValues[i] = data[i].split(',');
   if(dataValues[i].length != columns) {
      throw Exception("Wrong number of columns for row: "+i);
   }
   for(int j = 0; j < columns; j++) {
     try {
       board[row][column] = Integer.parseInt(dataValues[i][j]);
     } catch (NumberFormatException e) {
       throw Exception("Invalid value for ["+i+","+j+"]");
     }
   }
}

You have stated that you first accept number of rows and columns, hence before you start reading the numbers, you know the dimensions of the table. 您已声明首先接受行数和列数,因此在开始读取数字之前,您知道表的尺寸。

So you really just need to logic wether to update rows, or columns, depending on the mode you are running in. Below is an incomplete example. 所以你真的需要逻辑更新行或列,这取决于你运行的模式。下面是一个不完整的例子。

Hopefully, it gives you an idea on how to accomplish it. 希望它能让您了解如何实现它。

public class SplitInputExample {

    int maxRows = 3;
    int maxCols = 3;
    int board[][] = new int[3][3];
    boolean interpretRowise = true;

    private void initialize() {
        for (int i = 0; i < maxRows; i++) {
            board[i] = new int[maxCols];
        }

    }

    /**
     * 
     * @param string input
     * @param rowByRow if true, parse row by row, if false parse col by col
     * @param index index of row/col to update i.e if updating 2nd col, pass 1
     */
    public void split(String string, boolean rowByRow, int index) {

        int limit = 0;
        if (rowByRow){
            limit = maxRows;
        }else{
            limit = maxCols;
        }
        String splitArray[] = string.split(",");
        int inputArray[] = new int[splitArray.length];

        //save the parsed input in an int array
        int counter = 0;
        for (String s: splitArray){
            inputArray[counter++] = Integer.parseInt(s);
        }

        //checks for ensuring input array is of equals rows/cols
        for (int i=0; i<limit; i++){
            //either check rows or cols
            if (rowByRow){
                //fix the row
                board[index][i] = inputArray[i];
            }else{
                //fix the col
                board[i][index] = inputArray[i];
            }
        }

    }

    public void print(){
        for (int row[]: board){
            for(int col: row){
                System.out.print(col);
            }
        }
    }

    public static void main(String args[]) {
        String input[] = {
            "1,2,3",
            "4,5,6",
            "7,8,9"
        };
        SplitInputExample example = new SplitInputExample();

        int index = 0;
// parse row-wise i.e 1,2,3 are values of row 0, for each column
        for (String s: input){
            example.split(s,true,index++);
        }
        example.print();
        System.out.println("\n");

        index = 0;
//reset index to 0 and parse column-wise i.e 1,2,3 are values of column 0 for each row
        for (String s: input){
            example.split(s,false,index++);
        }

        example.print();
    }
}

Here is the solution: 这是解决方案:

    public static int getInputByRow(int[][] board, int v)
{

            for (int i=0; i<board.length; i++){
                int j=0;        
                String line = myInput.next();
                String[] splitarr = line.split(",");

                        for (String num : splitarr){                        
                                v = Integer.parseInt(num);
                                board[i][j++] = v;  
                        }
}

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

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