1

When I am printing contents of a string array the output is printing 'null' as well. I am not sure what's wrong with this. Here is the output, what I expect is the output without 'null'

null(wa?>=0)nullnull*(wo?>=0)nullnull*(4*wa?+7*wo?>=50)nullnull*(d1=10)nullnull*((d2=1)+(k=2))nullnull

Thanks and appreciate your help. I would say my skill in Java in beginner level and I started two weeks back.

Here is the actual code:

        String[] arrStr = new String[50];
        int countStr = 0;

        for (int i = 0; i < para.length; i++) {
            if (para[i] == '(') {
                count = count + 1;
            }
            if (para[i] == ')') {
                count = count - 1;
            }
            if (count > 0) {
                arrStr[countStr] = arrStr[countStr] + para[i];
            } else {
                if (para[i] == ')') {
                    arrStr[countStr] = arrStr[countStr] + para[i];
                    countStr += 1;
                } else {
                    countStr += 1;
                    arrStr[countStr] = arrStr[countStr] + para[i];
                    // System.out.println(para[i]);
                }
            }
        }
        System.out.println(countStr);

        for (int i = 0; i < countStr; i++) {
            System.out.print(arrStr[i]);
        }

Before this part, I am reading the following string from a word document:

(wa?>=0)AND(wo?>=0)AND(4*wa?+7*wo?>=50)AND(d1=10)AND((d2=1)+(k=2))

I think the problem may be due to the line:

arrStr[countStr] = arrStr[countStr] + para[i]; 

Since arrStr[countStr] is null initially and I add an element to it, it saves it as null+para[i]. Do you think it is possible?

Like when I try: System.out.println(arrStr[0]); I get the output as

null(wa?>=0)
4

3 回答 3

3
System.out.println(null + "Bla");

prints nullBla. A null represented as String is "null". The issue here is that initially all your String[] is made of null. You need to initialize them first. Typically,

Arrays.fill(arrStr, "");

Should do.

于 2013-05-27T16:04:22.357 回答
0

If any element in arrStr is null while printing, it will print that faithfully.

Without knowing specifics in your code, you can either ensure that no element in your array becomes null (ensure that the lengths match up and you're not skipping element in arrStr, or check for null before printing the element.

于 2013-05-27T15:45:55.800 回答
0

You don't initialize the values of the arrStr array, you just allocate size for it, so each element of the array is null. When you assign a value to an element of the array, you concatenate its value (which is null) with the value of para[i].

You should initialize your array before using it:

String[] arrStr = new String[50];
for (int i = 0; i < arrStr.length; i++) {
    arrStr[i] = "";
}
于 2013-05-27T16:04:46.523 回答