java程序中if语句的作用域错误 [英] scope error in if statement in java program

查看:198
本文介绍了java程序中if语句的作用域错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在if语句中遇到问题,至少,我很确定这是我的错误所在,而且我不确定如何解决这个问题(我很擅长编程)。

I'm having an issue with scope in an if statement, at least, I'm pretty sure that is where my error is, and I'm not sure of how to fix the issue (I'm pretty new at programming).

基本上,似乎如果我在if语句中声明了某些内容,那么变量(在本例中是一个结构数组)在if语句之外就不存在了。但是,我真的需要将数组的声明放在if / else中,因为数组的大小取决于N,那么我该如何解决这个错误呢?

Basically, it seems that if I declare something within an if statement, the variable (in this case, an array of structs) does not exist outside of the if statement. However, I really need the declaration for the array to be inside of an if/else because the size of the array is dependent upon N, so how can I fix this error?

程序是用Java编写的,我正在使用Eclipse。非常感谢任何见解。

The program is in Java, and I'm using Eclipse. Any insight is greatly appreciated.

//declare an int (used in determining array length)
int N = 4;

//declare instance of MyClass
MyClass myClass = new MyClass();

//declare and array, then initialize each struct in that array
        if(N <= 26){
            MyStruct array[] = new MyStruct[260];
            for(int i = 0; i < array.length; i++){
                array[i] = new MyStruct();
            }
        }

        else{
            MyStruct array[] = new MyStruct[N*10];
            for(int i = 0; i < array.length; i++){
                array[i] = new MyStruct();
            }

//lots of other code goes here of stuff that needs to be done before myMethod can be called

//call a method in myClass that requires 'array' to be passed in
myClass.myMethod(array);     // ERROR - ARRAY CANNOT BE RESOLVED TO BE A VARIABLE


推荐答案

您需要移动 MyStruct数组[]; 块。你回答了自己的问题,事实上,当你在一个块中声明一个局部变量(一段由 {} 包围的代码)时,该变量只会在块,根据Java语言的范围规则。

You need to move the array declaration MyStruct array[]; outside of the if block. You answered your own question, in fact, when you declare a local variable inside a block (a piece of code surrounded by {}), the variable will only be visible inside that block, as per the scoping rules of the Java language.

你可以做什么里面 如果 else blocks,将数组实例化为正确的大小,如下所示:

What you can do inside the if or else blocks, is instantiating the array to the correct size, like this:

MyStruct[] array;

if (N <= 26) {
    array = new MyStruct[260];
    for (int i = 0; i < array.length; i++) {
        array[i] = new MyStruct();
    }
}

else {
    array = new MyStruct[N*10];
    for (int i = 0; i < array.length; i++) {
        array[i] = new MyStruct();
    }
}

更短的解决方案是:

MyStruct[] array = new MyStruct[N <= 26 ? 260 : N*10];
for (int i = 0; i < array.length; i++) {
    array[i] = new MyStruct();
}

这篇关于java程序中if语句的作用域错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆