拆分字符串并将其放在 int 数组中 [英] Splitting String and put it on int array

查看:37
本文介绍了拆分字符串并将其放在 int 数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须输入一个带有数字的字符串,例如:1,2,3,4,5.这是输入的一个示例,然后我必须将它放入一个 INT 数组中,这样我才能对其进行排序,但没有按照应有的方式工作.

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);
        }
    }
}

推荐答案

对于输入 1,2,3,4,5 输入长度为 9. 9/2 = 4 在整数数学中,因此您只存储前四个变量,而不是全部 5 个.

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.

即使你修复了它,如果你传入 10,11,12,13

Even if you fixed that, it would break horribly if you passed in an input of 10,11,12,13

如果你使用 1,2,3,4,50 作为输入,它会工作(偶然),奇怪的是 :-)

It would work (by chance) if you used 1,2,3,4,50 for an input, strangely enough :-)

你最好做这样的事情

String[] strArray = input.split(",");
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
    intArray[i] = Integer.parseInt(strArray[i]);
}

为了将来参考,当您遇到错误时,我强烈建议将其与代码一起发布.你可能没有一个拥有 jdk 的人可以随时编译代码来调试它!:)

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

这篇关于拆分字符串并将其放在 int 数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆