Java 从数组生成变量以创建循环

Java 从数组生成变量以创建循环,java,arrays,loops,Java,Arrays,Loops,所以我有一个数组,我在从文本文件读取和拆分变量时生成这个数组。然后,我需要将数组中的split变量解析为一个整数,并用try-catch将其包围起来,以防数据不是整数。我试图避免为数组中的每个变量创建try-catch块。这是我目前的代码: String [] tempList = data.split("-"); String [] variables = {"readerNo", "seconds", "minutes", "hours",

所以我有一个数组,我在从文本文件读取和拆分变量时生成这个数组。然后,我需要将数组中的split变量解析为一个整数,并用try-catch将其包围起来,以防数据不是整数。我试图避免为数组中的每个变量创建try-catch块。这是我目前的代码:

String [] tempList = data.split("-");

String [] variables = {"readerNo", "seconds", "minutes", "hours", 
                       "days", "month", "year", "other","empNo"};
int readerNo, seconds, minutes, hours, days, month, year,other, empNo;
/*
* parsing of data to integers/boolean
*/

//-----------
for(int i = 0; i < variables.length; i++) {
    try{
        *variable name should be here* = Integer.parseInt(tempList[i]); 
    }catch(Exception E){
        *variable name should be here* = -1; 
    }
}
String[]templast=data.split(“-”);
String[]变量={“readerNo”、“seconds”、“minutes”、“hours”,
“日”、“月”、“年”、“其他”、“empNo”};
int readerNo、秒、分、时、日、月、年、其他、empNo;
/*
*将数据解析为整数/布尔值
*/
//-----------
对于(int i=0;i

是否可能,或者是否需要为每个对象创建一个try-catch块?

尝试这样做:

int[] myNumbers = new int[tempList.length];
for(int i = 0; i < tempList.length; i++){
  try{
     myNumbers[i] = Integer.parseInt(tempList[i]); 
  }catch(Exception E){
     myNumbers[i] = -1; 
  }
}
int[]myNumbers=newint[templast.length];
for(int i=0;i

这是避免try{}-块的方法:)

我认为一个好方法是使用正则表达式:

if(tempList[i].matches("-?\\d+"))
{
  Integer.parseInt(tempList[i]); 
}

有几种方法可以检查字符串是否表示整数。如果您想避开该异常,您需要在尝试解析之前知道它是一个int。相关信息请参见此处:

他写道,他希望避免为每个变量编写try-catch:)感谢您的提示:)这是不同的,因为他为每个变量使用自己的整数。我只使用了一个整数[]我想他想让人像我一样回答这个问题,因为他有8个整数。检查这个问题/答案:捕捉异常是不好的做法,而不是捕捉数字格式异常。你是对的@Raphaël。坏习惯。