拆分字符串,并把它int数组上 [英] Splitting String and put it on int array

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

问题描述

所以,我必须输入与数字前的字符串:1,2,3,4,5
这就是输入的样本,那么我必须把在一个int数组,所以我可以排序,但没有工作,那么应该工作的方式,感谢您的帮助。)

 包装组合;进口java.util.Scanner中;公共类Array {    公共静态无效的主要(字串[] args){
        字符串输入;
        INT长,计数,大小;
        扫描仪键盘=新的扫描仪(System.in);
        输入= keyboard.next();
        长度= input.length();
        尺寸=长度/ 2;
        INT intarray [] =新的INT [大小]
        字符串strarray [] =新的String [大小]
        strarray = input.split(,);
                为(计数= 0; COUNT< intarray.length;计数++){
            intarray [统计] =的Integer.parseInt(strarray [计数]);
        }        对于(int类型:intarray){
            的System.out.println(多个);
        }
    }
}


解决方案

有关输入 1,2,3,4,5 输入是长度9. <$的C $ C> 9/2 = 4 在整数运算,所以你只存储第一四个变量,并不是所有的5。

即使你固定的,如果你的输入通过,将打破可怕的 10,11,12,13

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

您会好得多做这样的事情。

 的String [] = strArray input.split();
INT [] intArray =新INT [strArray.length]
的for(int i = 0; I&LT; strArray.length;我++){
    intArray [I] =的Integer.parseInt(strArray [I]);
}

有关备查,当你得到一个错误,我强烈建议用code张贴。您可能没有有人用现成的编译code调试它一个JDK! :)

So I have to input a string with numbers ex: 1,2,3,4,5 thats 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, thanks for the help :).

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

解决方案

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

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

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