Splitting String and put it on int array

后端 未结 8 1401
眼角桃花
眼角桃花 2020-11-28 14:03

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

8条回答
  •  隐瞒了意图╮
    2020-11-28 14:51

    Let's consider that you have input as "1,2,3,4".

    That means the length of the input is 7. So now you write the size = 7/2 = 3.5. But as size is an int, it will be rounded off to 3. In short, you are losing 1 value.

    If you rewrite the code as below it should work:

    String input;
    int length, count, size;
    Scanner keyboard = new Scanner(System.in);
    input = keyboard.next();
    length = input.length();
    
    String strarray[] = input.split(",");
    int intarray[] = new int[strarray.length];
    
    for (count = 0; count < intarray.length ; count++) {
        intarray[count] = Integer.parseInt(strarray[count]);
    }
    
    for (int s : intarray) {
        System.out.println(s);
    }
    

提交回复
热议问题