I have to input a string with numbers ex: 1,2,3,4,5. That's a sample of the input, then I have to put that in an array of INT so I can sort it but is not working the way it should work.
package array; import java.util.Scanner; public class Array { public static void main(String[] args) { String input; int length, count, size; Scanner keyboard = new Scanner(System.in); input = keyboard.next(); length = input.length(); size = length / 2; int intarray[] = new int[size]; String strarray[] = new String[size]; strarray = input.split(","); for (count = 0; count < intarray.length ; count++) { intarray[count] = Integer.parseInt(strarray[count]); } for (int s : intarray) { System.out.println(s); } } }
Use split(delimiter) to Split String to an Array in Java We need to pass the delimiter to split the string based on it. The split() method would break the string on every delimiter occurrence and store each value in the array.
For input 1,2,3,4,5
the input is of length 9. 9/2 = 4
in integer math, so you're only storing the first four variables, not all 5.
Even if you fixed that, it would break horribly if you passed in an input of 10,11,12,13
It would work (by chance) if you used 1,2,3,4,50
for an input, strangely enough :-)
You would be much better off doing something like this
String[] strArray = input.split(","); int[] intArray = new int[strArray.length]; for(int i = 0; i < strArray.length; i++) { intArray[i] = Integer.parseInt(strArray[i]); }
For future reference, when you get an error, I highly recommend posting it with the code. You might not have someone with a jdk readily available to compile the code to debug it! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With