【问题标题】:Split() method in Java for multi-dimensional arrayJava中用于多维数组的Split()方法
【发布时间】:2012-10-20 00:45:16
【问题描述】:

我有一个二维数组。任务是接受用户的行号和列号,如果用户想逐行(或逐列)输入数字数据,他必须用逗号来完成。例如,3x3 将是:

1,2,4

2,5,3

5,3,2

所以第一行元素将是[0,0]=1 [0,1]=2 [0,2]=3,第二行[1,0]=2 [1,1]=5 [ 1,2]=3 等。 我知道我应该用字符串来做到这一点,然后将其拆分为“,”,然后将其转换为非整数,但我不知道在这种情况下如何拆分。

这就是我的行输入:

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();
            }
        }
     }  

【问题讨论】:

    标签: java


    【解决方案1】:

    我认为这就是你想要的,假设 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");
       }
    }
    

    对于逐行插入:

    //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+"]");
         }
       }
    }
    

    【讨论】:

    • 嗨菲利普,首先感谢您的回答。我的意思是用户必须提供许多行和列(2x2、4x4、9x9 ...)。比,他必须逐行或逐列输入逗号分隔的数据。如果他有三行,那么他必须输入三行,此时每行将包含三个以逗号分隔的元素。我必须将每个元素放在二维数组 (board[][]) 中的位置。之后我将不得不进行一些计算,例如检查列中是否有重复的数字,但这是另一个问题:)
    • 听起来像一个缩小的数独 :-) 更新了我的答案
    • 是的,它是数独的轻量版 :)
    【解决方案2】:

    您已声明您首先接受行数和列数,因此在开始阅读数字之前,您知道表格的尺寸。

    所以你真的只需要根据你运行的模式来逻辑更新行或列。下面是一个不完整的例子。

    希望它能让您了解如何完成它。

    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();
        }
    }
    

    【讨论】:

      【解决方案3】:

      解决方法如下:

          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;  
                              }
      }
      

      【讨论】:

      • 添加一些解释总是好的,而不仅仅是一堆代码行。请注意,第一个 for 未关闭(或 method 取决于视图),它缺少关闭 }
      猜你喜欢
      • 2021-12-21
      • 2017-03-26
      • 2011-12-17
      • 2015-05-27
      • 2022-01-22
      • 2016-06-22
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多