程序运行与在netbean中显示进度条但结果不来

时间:2015-08-17 07:37:29

标签: java arrays

如果所有元素都是1或2,我将数组定义为121数组,它以一个或多个1开头,后跟一个或多个2,并以相同数量的1开始。

然而,当我运行程序时,我没有得到结果。如果程序没问题,我必须得到给定数组{1,1,2,2,2,1,1}的结果1。

请帮帮我。

 public class OneTwoOne {

public static void main(String[] args) {

    System.out.println(OneTwoOne.is121Array(new int[]{1, 1, 2, 2, 2, 1, 1}));
}

public static int is121Array(int[] a) {

    int i, t1 = 0, t2 = 0, te = 0, tb = 0, tc = 0;
    for (i = 0; i < a.length; i++) {//checking 1's and 2's in an array

        if (a[i] == 1) {

            t1 = 1;
        }
        if (a[i] == 2) {
            t2 = 2;
        }
    }

    for (i = 0; i < a.length; i++) {//counting number of 1's at begining of array

        while (a[i] == 1) {

            tb++;
        }
        break;
    }

    for (i = a.length; i >= 0; i--) {//counting number of 1's at end of array

        while (a[i] == 1) {
            te++;
        }
        break;
    }

    for (i = 0; i < a.length; i++) {//counting total number of 1's in an array

        if (a[i] == 1) {
            tc++;
        }
    }

    if (t1 > 0 && t2 > 0 && t1 == t2 && te + tb == tc) {
        //1's and 2's must be greater thna 0 and begining 1's and end 1's must be equal 
        //their sum is equal to total 1's in an array
        return 1;
    } else {
        return 0;
    }
}
}

1 个答案:

答案 0 :(得分:0)

你正在使用while循环而不是&#34;如果&#34;同样,for循环限制也不必要地足够长,导致错误的结果。我对你的方法做了一些改动:

var res = "P18DT5H2M3S";
var tokens = res.split(/[A-Z]+/);
//var str = "D:"+token[1]+" H:"+tokens[2]+" M:"+tokens[3]+" S:"+tokens[4];
alert("D:"+tokens[1]+" H:"+tokens[2]+" M:"+tokens[3]+" S:"+tokens[4]);

您可以运行此程序here。您可以访问完整代码here