开发者社区> 问答> 正文

如何在while循环外使用声明数组,但在while循环中初始化数组?

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

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

}

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

展开
收起
小六码奴 2019-10-10 17:28:39 846 0
1 条回答
写回答
取消 提交回答
  • 我对你的代码进行了一些简化,并为其提供了“测试”上下文(简单的main)。

    我放置了适当的注释,以便你可以更轻松地跟踪代码。

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

    } 此外,c,d和cIP毫无意义的名字。尝试给变量赋予更有意义的名称。

    2019-10-10 17:29:08
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
用计算和数据去改变整个世界 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载