Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting String and put it on int array

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);         }     } } 
like image 338
user1076331 Avatar asked Dec 01 '11 21:12

user1076331


People also ask

How do you store a split value in an array?

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.


1 Answers

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! :)

like image 147
corsiKa Avatar answered Sep 21 '22 23:09

corsiKa