写bug的小杨

导航

break语法使用

public static void main(String[] args) {
        int[] asteroids=new int[]{-2,-2,2,-1};
        Stack<Integer> stack=new Stack<>();
        for(int star:asteroids){
            collision:{
                // 右侧的行星==>负数    栈顶元素==>正数
                while(!stack.isEmpty() && star<0 && stack.peek()>0){
                    int top = stack.peek();
                    // 如果右侧的行星大 则 栈顶元素毁灭
                    if(top<-star){
                        stack.pop();
                        // 加上continue可以继续while循环
                        // 不加continue会走到break collision,跳出整个collision块
                        continue;
                    }
                    // 如果 两者相等 则 一起毁灭
                    else if(top==-star){
                        stack.pop();
                    }
                    // 如果左侧的行星大 则 跳出循环,collision代码块结束 => 自我毁灭吧
                    break collision;
                }
                stack.push(star);
            }
        }
    }

  

posted on 2022-01-30 15:38  迷途的小狗  阅读(48)  评论(0编辑  收藏  举报