java解析Joptionpane中的多个int
我试图练习一些java,但我感到困惑。我试图在一个3*3数组中输入多个数字,但是当我运行我的程序时,我得到一个兼容错误(线程“main”java.lang.NumberFormatException中的异常)?如何将多个int从Joptionpane解析到数组中
public static int[][] enterMatrix() {
String NumberstoParse = JOptionPane.showInputDialog("Enter list: ");
int UserInput = Integer.parseInt(NumberstoParse);
int[][] matrix = new int[3][3];
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = UserInput;
return matrix;
}
}
# 1 楼答案
Alex在下面已经添加了一些代码,这些代码将处理一些边界线问题,有些测试用例包括一些测试用例。代码是有文档记录的,我希望这有助于
# 2 楼答案
我认为主要的问题是在解析JOptionPane中的字符串时。整数parseInt()看到逗号并抛出NumberFormatException。可能值得对该方法进行一些测试,可能是使用JShell
在这里,我获取了输入字符串“1,2,3,4,5,6,7,8,9”,并使用方法从类字符串中拆分来生成一个字符串数组,该字符串数组由(“,\s+”)拆分。这意味着,围绕匹配的正则表达式进行拆分,这里的正则表达式是“一个逗号和一个或多个空格字符”。然后使用Integer处理数组中的每个字符串。parseInt()