【问题标题】:How to I use declare an array outside a while loop but initialize it in the while loop?如何在while循环外使用声明数组但在while循环中初始化它?
【发布时间】:2019-10-10 05:38:31
【问题描述】:

我正在尝试在我的代码中使用一个数组,但它的初始化方式会因其他一些因素而有所不同。

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


    }
}

当我说我希望数组存在多长时间时,它给了我错误“令牌上的语法错误,删除这些令牌”。它还说数组常量只能在初始化程序中使用..

【问题讨论】:

  • d= new char[1] 缺少;
  • d= new char[1]后面加一个分号,把d={cIP[cIP.length-1]};改成d[0] = cIP[cIP.length-1];你可以用System.arraycopy替换那行下面的循环
  • 另外d={cIP[cIP.length-1]}; 不是有效的数组语法。
  • 你可以做到d = new char[] { cIP[cIP.length-1] };(不需要d=new char[1]))。但是为什么要使用一个数组来存储一个char?在for循环之前也缺少cc = new char[cIP.length-2])的初始化,
  • 我正在使用一个数组,因为数组 d 也可以是几个字符,具体取决于点所在的位置(我在下面的其他循环中这样做了,但有同样的问题。

标签: java arrays loops scope declaration


【解决方案1】:

我已经稍微简化了你的代码,并给它一个“测试”上下文(简单的 main)。

我已经放置了适当的 cmets,以便您可以更轻松地跟踪代码。

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

另外,cdcIP 是毫无意义的名称。试着给你的变量起更有意义的名字。

【讨论】:

  • 非常感谢,我不知道你可以做 Arrays.copyOf ,所以帮助很大!我会尝试你使用函数 invokeMethod 所做的事情并让你保持更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
  • 2011-07-12
  • 2015-10-10
  • 1970-01-01
  • 2016-05-29
相关资源
最近更新 更多