如何在PROCESSING中创建一个包含Integer值(而不是int)的Dynamic数组。
我已将String存储到文本文件中(String Str =“12,13,14,15”)。现在我需要在加载文本文件后将它们拆分并转换为Integer类型。
答案 0 :(得分:2)
由于代码正在读取文件,我会改为使用Scanner:
String str = "2,3,4,5,6,7";
List<Integer> intList = new ArrayList<Integer>();
Scanner sc = new Scanner(new File(/*yourFile*/));
//Scanner sc = new Scanner(str);
while(sc.hasNext()) {
sc.useDelimiter(",");
intList.add(sc.nextInt());
}
Integer[] wrapperArray = new Integer[intList.size()];
intList.toArray(wrapperArray);
扫描仪:How-to
答案 1 :(得分:2)
你可以尝试这个代码..它适用于我
try {
FileReader fr = new FileReader("data.txt");
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
String strArray[] = str.split(",");
Integer intArray[] = new Integer[strArray.length];
for (int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
System.out.println(intArray[i]);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
我希望这会对你有所帮助。
答案 2 :(得分:1)
String str = "12,13,14,15";
String[] strArray = str.split(",");
int[] intArray = new int[strArray.length];
for (int i = 0; i < strArray.length; i++) {
try {
intArray[i] = Integer.parseInt(strArray[i]);
} catch (NumberFormatException e) {
// Handle the exception properly as noted by Jon
e.printStackTrace();
}
}