Java变量作用域在循环内部和外部

huangapple go评论62阅读模式
英文:

Java variable scope in and outside loop

问题

以下是翻译好的部分:

我最近在一个在线Java测试中编写了这段代码。它位于一个被设置为返回整数的方法内部。我收到了一个类似于“变量a没有被赋值”的错误消息。我觉得这很奇怪,因为for循环必须能够访问方法的变量,并且循环内的赋值必须被注册,对吗?

int a;
for(int i=1; i<5; i++){
    a = i;
}
return a;

我原本以为这个方法会返回整数5。

这只是关于变量a作用域的问题。我知道这段代码没有意义。

英文:

I wrote this code in an online java test recently. It was inside a method that was set to return an integer. I got an error message something like "variable a has no value assigned to it". I find this odd because the forloop must have access to the methods variable and the assignments inside of the loop must be registered right?

int a;
for(int i=1;i&lt;5;i++){
    a = i;} 
return a;

I did assume that the method would return the integer 5.

This is only a question regarding scope of the variable a. I know that the code makes no sense.

答案1

得分: 0

你可以尝试下面的代码,这将对你有所帮助。对于任何变量要返回或保存任何值,初始化是必需的。

    class a{
        public static void main(String[] args) {
            System.out.println(test());
        }
        public static int test(){
            int a = 0;
            for(int i=1;i<5;i++){
                a = i;}
            return a;
        }
    }
英文:

You can try below code , that will help you. Initialisation is mandatory for any variable to return or hold any value.

class a{
    public static void main(String[] args) {
        System.out.println(test());
    }
    public static int test(){
        int a = 0;
        for(int i=1;i&lt;5;i++){
            a = i;}
        return a;
    }
}

huangapple
  • 本文由 发表于 2020年8月25日 21:42:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63580177.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定