comma delimited list of numbers and grouping the numbers into they are sequential arrange

时间:2017-06-14 10:28:07

标签: java

the question was write a program the will do the comma delimited list of numbers,grouping the numbers into a range when they are sequential. given the Input:

1,2,6,7,8,9,12,13,14,15,21,22,23,24,25,31

and expected output:

"[[1],[2], [6,7,8], [13,14,15], [21-25], [32]]"

and i wrote a simple code like this

public static void main(String []args){
        String input = "1,3,6,7,8,9,12,13,14,15,21,22,23,24,25,31";
        String []num = input .split(",");
        String temp = "[";
        int min = 1;
            for(int i =0; i <num.length;i++){
                if(num[1] == num[0]){
                    temp = temp + num[i]+"]";
                }else if (num[min+1] != num[i]){
                    temp = temp + "," +num[i];
                }else{
                    temp = "]";
                }
                System.out.print(temp);
            }
    }

when i run this code it give me the following output:

[,1[,1,3]],7],7,8],7,8,9],7,8,9,12],7,8,9,12,13],7,8,9,12,13,14],7,8,9,12,13,14,15],7,8,9,12,13,14,15,21],7,8,9,12,13,14,15,21,22],7,8,9,12,13,14,15,21,22,23],7,8,9,12,13,14,15,21,22,23,24],7,8,9,12,13,14,15,21,22,23,24,25],7,8,9,12,13,14,15,21,22,23,24,25,31]

1 个答案:

答案 0 :(得分:0)

这是作业吗?尽量自己动手解决作业!

我认为您的一个问题是您将数字作为字符串处理,并且字符串的比较仅比较引用! 请考虑以下代码:

String a =  new String("1");
String b = "1";

System.out.println("a: "+a+" b: "+b);
System.out.println(a==b);

输出如下:

a: 1 b: 1
false

即使字符串具有完全相同的内容,它们也不会引用同一个对象,因此您无法确定您比较的字符串是否相等!字符串应与equals()方法进行比较。

无论如何,您应该首先通过执行

将数字转换为int []数组
String[] strs = input.split(",");

int[] ints = new int[strs.length()];
for(int i = 0;i<ints.length;i++){
    ints[i] = Integer.parseInt(strs[i]);
}

或者通过在java 8中使用功能元素:

int[] integers = Arrays.stream(input.split(",")).map(Integer::parseInt).mapToInt(i->i).toArray();

然后你可以比较它们并且100%确定比较是正确的。