How can I create a Dynamic array that holds Integer values (not int) in PROCESSING.
I have stored the String into a text file (String Str= "12,13,14,15"). Now i need to split and convert them to Integer type after loading the text file.
How can I create a Dynamic array that holds Integer values (not int) in PROCESSING.
I have stored the String into a text file (String Str= "12,13,14,15"). Now i need to split and convert them to Integer type after loading the text file.
Since code is reading a file, I would use a Scanner instead:
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);
Scanner: How-to
You can try this code.. It works fine for me
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();
}
I hope this will help you.
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();
}
}