我试图练习一些java而且我很困惑。我试图将多个数字输入一个3 * 3数组,但是当我运行我的程序时,我得到一个compliation错误(线程“main”java.lang.NumberFormatException中的异常)?如何从Joptionpane解析多个int到数组?
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;
}
}
答案 0 :(得分:0)
我认为主要问题是从JOptionPane解析String时。 Integer.parseInt()查看逗号并抛出NumberFormatException。可能值得对这个方法进行一些测试,可能还有JShell!
这里,我已经输入了字符串“1,2,3,4,5,6,7,8,9”并使用了从类String中拆分的方法来生成一个由(“,” \ S +“)。这意味着,围绕匹配的正则表达式进行拆分,这里是“逗号和一个或多个空白字符”。然后使用Integer.parseInt()处理数组中的每个字符串。
public static int[][] enterMatrix() {
String numberstoParse = JOptionPane.showInputDialog("Enter list: ");
String[] splitNumbers = numberstoParse.split(",\\s+");
int[][] matrix = new int[3][3];
int ctr = 0;
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = Integer.parseInt(splitNumbers[ctr]);
ctr++;
}
return matrix;
}
答案 1 :(得分:0)
添加到Alex已经添加的内容是代码,它将处理一些边界线问题,有些测试用例包括一些测试用例。代码记录在案,我希望这有帮助...
public class Dummy
{
public static void main(String[] args)
{
String temp = "";
for(int x = 0; x <10; x++){
temp = temp + x+"";
int[][] matrix = enterData(temp);
System.out.println("Given Input:" + temp);
if(matrix != null){
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix[i].length; j++)
System.out.print(matrix[i][j] + " ");
System.out.println();
}
}
System.out.println("-------------");
temp +=",";
}
}
//Once you understand the test cases, you can remove the argument and use the JOptionPane for input
public static int[][] enterData(String input)
{
//TODO: Please user JOPtionPane I have added this just to make the test cases work
//String input = JOptionPane.showInputDialog("Enter list: ");
//This will split the Input on the basis of ","
String[] inputArr = input.split(",");
//Variable has a counter which which will represent the number of inputs received
int inputArrCount = 0;
int[][] matrix = new int[3][3];
//If the size is greater than 9, then as u suggested an error is printed
if(inputArr.length > 9 ){
System.err.println("Number length > 9");
return null;
}
for(int i = 0; i <matrix.length; i++){
for (int j = 0; j < matrix[i].length; j++){
//If to just track that inputArrCount never goes beyond the inputArr elements
if(inputArrCount < inputArr.length){
int temp = Integer.parseInt(inputArr[inputArrCount++]);
matrix[i][j] = temp;
}
}
}
return matrix;
}
}