您已声明您首先接受行数和列数,因此在开始阅读数字之前,您知道表格的尺寸。
所以你真的只需要根据你运行的模式来逻辑更新行或列。下面是一个不完整的例子。
希望它能给你一个关于如何完成它的想法。
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();
}
}