使用此程序迭代并使用switch case

时间:2015-01-06 10:37:51

标签: while-loop stack switch-statement

如果选项无效,我想重复您的选择,但它正在退出。

有人可以帮忙吗?

class Stackdemo1 {
    public static void main(String []args)throws IOException {
        Stack<Integer> st=new Stack<Integer>();
        BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
        int element,pos;
        int choice=0;  
        while(choice<4) {
            System.out.println("stack operation");
            System.out.println("1 push element");
            System.out.println("2 pop element");
            System.out.println("3 search for element");
            System.out.println("4 exit");
            System.out.println("your choice");
            choice=Integer.parseInt(br.readLine());

            switch(choice) {
                case 1:
                    System.out.print("enter element:");
                    element =Integer.parseInt(br.readLine());
                    st.push(element);
                    break;
                case 2:
                    Integer i=st.pop();
                    System.out.print("poped="+i);
                    break;
                case 3:
                    System.out.print("enter element");
                    element=Integer.parseInt(br.readLine());
                    pos=st.search(element);

                    if(pos== -1)
                        {
                             System.out.println("element not found");
                        } else
                             System.out.println("element found position:"+pos);
                    break;
                 default:
                    System.out.println("enter other number");     
                    continue;                          

             }
             System.out.println("Stack="+st);
        }
    }       
}

输出:

    D:\work>javac Stackdemo1.java

    D:\work>java Stackdemo1
    stack operation
    1 push element
    2 pop element
    3 search for element
    4 exit
    your choice
    5
    enter other number

1 个答案:

答案 0 :(得分:0)

您输入了5作为值,并且在循环条件下,它是while(选择&lt; 4)并不满足。希望它能解开这个谜团。