简体   繁体   中英

How to I use declare an array outside a while loop but initialize it in the while loop?

I am trying to use an array in my code but it gets initialized differently depending on some other factors.

char[] d;
char[] c;
if (cIP.length>6&&cIP.length<16)
{
    IP=true;
    if (cIP[cIP.length-2]=='.')
    {
        d= new char[1];
        d={cIP[cIP.length-1]};
        c=new char[cIP.length-2];
        for (int i=0;i!=cIP.length-2;i++)
        {
            c[i]=cIP[i];
        }


    }
}

It gives me the error 'Syntax error on tokens, delete these tokens' for when I say how long I want the arrays to be.. It also says that array constants can only be used in initializers..

I've simplified your code a bit and gave it a "testing" context (simple main).

I've placed appropriate comments so you can track the code more easily.

public static void main(String[] args) {
    System.out.println("if statement not triggered");
    invokeMethod(new char[]{'a', 'b', 'c', 'd', 'e'});

    System.out.println("if statement triggered");
    invokeMethod(new char[]{'a', 'b', 'c', 'd', 'e', '.', 'g'});
}

private static void invokeMethod(char[] cIP) {
    // a suggestion is to initialize your arrays to default values 
    // (i.e. if statement is not triggered). In this case, I've 
    // initialized them to a empty arrays.
    char[] d = new char[]{};
    char[] c = new char[]{};

    // since you are using cIP.length several times, 
    // assign it to a variable for easier understanding/usage
    int size = cIP.length;
    if (size > 6 && size < 16) {
        if (cIP[size - 2] == '.') {
            // You can use this one-liner to set d to one character.
            // Essentially, your code, just merged into one-liner
            d = new char[]{cIP[size - 1]};
            // instead of char-by-char copying in a loop
            // you can use Arrays.copyOf()
            c = Arrays.copyOf(cIP, size - 2);
        }
    }

    System.out.println(c);
    System.out.println(d);
}

Also, c , d and cIP are meaningless names. Try to give your variables more meaningful names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM