문제

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

다른 팁

Quoting a comment on the question by Jim H.:

You returned from the pop() method. Anything after that is unreachable.

Unreachable code results in compiler error in Java.

In your program the line

int count2 = 0;

will never be reached since it is after the return statement.

Place this line above the return statement to work.

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]; .So your method does not necessarily reach int count2 = 0; because it assumed that the method already reached its goal.

The last statement in the function should be a return statement.

Linting tools would flag it since it messes with the allocation of new memory after the counter scope ends.

Declare before return myStack[0] that fixes

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top