简体   繁体   English

为什么这段代码会给出“无法访问的代码”错误?

[英]Why is this code giving an “unreachable code” error?

I can't seem to find a way to fix this problem.我似乎无法找到解决此问题的方法。 All i'm doing is declaring an integer and it's telling me that the code is unreachable.我所做的只是声明一个整数,它告诉我代码无法访问。

private class myStack{
    Object [] myStack = new Object[50];

    private void push(Object a){
        int count = 50;
        while(count>0){
            myStack[count]=myStack[count-1];
            count--;
        }
        myStack[0]=a;
    }

    private Object pop(){
        return myStack[0];
        int count2 = 0; //Unreachable Code
    }   
}

Once you return from a method, you return to the method that called the method in the first place.一旦你return从一个方法,您返回到调用摆在首位的方法的方法。 Any statements you place after a return would be meaningless, as that is code that you can't reach without seriously violating the program counter (may not be possible in Java).您在返回之后放置的任何语句都将毫无意义,因为如果不严重违反程序计数器(在 Java 中可能不可能),您将无法访问这些代码。

Quoting a comment on the question by Jim H. :引用Jim H.对这个问题的评论:

You returned from the pop() method.您从 pop() 方法返回。 Anything after that is unreachable.之后的任何事情都无法访问。

Unreachable code results in compiler error in Java.无法访问的代码会导致 Java 中的编译器错误。

In your program the line在你的程序中

int count2 = 0;

will never be reached since it is after the return statement.永远不会到达,因为它在 return 语句之后。

Place this line above the return statement to work.将此行放在 return 语句上方以起作用。

The simple explanation in plain English would be the following:简单的英语解释如下:

 private Object pop(){
    return myStack[0];
    int count2 = 0; //Unreachable Code
} 

method private Object pop(){} is looking for a return type Object and you just gave that return type by writing return myStack[0];方法private Object pop(){}正在寻找返回类型Object而您只是通过编写return myStack[0];提供该返回类型return myStack[0]; .So your method does not necessarily reach int count2 = 0; .所以你的方法不一定达到int count2 = 0; because it assumed that the method already reached its goal.因为它假设该方法已经达到了它的目标。

The last statement in the function should be a return statement.函数中的最后一条语句应该是 return 语句。

Linting tools would flag it since it messes with the allocation of new memory after the counter scope ends. Linting 工具会标记它,因为它会在计数器范围结束后干扰新内存的分配。

在返回 myStack[0] 之前声明修复

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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