본문으로 바로가기

[java][이칙연산 계산기 (+,-)]

category JAVA 2018. 3. 20. 09:03

 

the space coding

 

 

LinkedList<Integer> numList = new LinkedList<Integer>();

        LinkedList<Character> opList = new LinkedList<Character>();

        

        Scanner sc = new Scanner(System.in);

        

        String s = sc.nextLine();

        

        String num = "";

        

        for(int i = 0; i < s.length(); i++)// s의 길이 만 큼 

        {

            char ch = s.charAt(i);

            

            if(ch == '+')

            {

                numList.add(Integer.parseInt(num));

                opList.add(ch);

                num = "";

                continue;

            }

            else if(ch == '-') 

            {

                numList.add(Integer.parseInt(num));

                opList.add(ch);

                num = "";    

                continue;

            }

            num += ch;

        }

        numList.add(Integer.parseInt(num));

 

        while(!opList.isEmpty()) {

            int prevNum = numList.poll();

            int nextNum = numList.poll();

            char op = opList.poll();

            

            if(op == '+') {

                numList.addFirst(prevNum + nextNum);

            } else if(op == '-') {

                numList.addFirst(prevNum - nextNum);

            }

        }

 

        System.out.println(numList.poll());


}


}



'JAVA' 카테고리의 다른 글

성적 관리 프로그램  (0) 2018.04.12
AVL트리 vs 편향트리  (0) 2018.03.27
[JAVA][래퍼클래스]  (0) 2018.03.22
[JAVA][Stack / Queue]  (1) 2018.03.21
JAVA 단 축 키  (0) 2018.03.21