코락 CoRock
코딩하는 락스타
코락 CoRock
  • 분류 전체보기 (393)
    • frameworks (19)
      • spring (19)
      • spring-boot (0)
      • testing (0)
    • languages (94)
      • java (39)
      • kotlin (0)
      • python (42)
      • r (13)
    • libraries (0)
    • programming (239)
      • android (13)
      • c (17)
      • cpp (22)
      • database (18)
      • design-pattern (4)
      • data-structures (11)
      • git (8)
      • hadoop (6)
      • html-css (7)
      • issue (4)
      • javascript (26)
      • jsp (34)
      • os (29)
      • php (6)
      • preferences (19)
      • etc (15)
    • discography (37)
      • k-pop (18)
      • pop (19)
    • blog (3)

블로그 메뉴

  • Programming
  • Java
  • JavaScript
  • Discography
  • K-Pop Songs
  • Pop Songs
  • Blog
  • Guestbook

공지사항

인기 글

태그

  • CentOS
  • 파이썬
  • jsp
  • oracle
  • Java
  • javascript
  • 자바스크립트
  • Spring
  • Android
  • python
  • linux
  • r

최근 댓글

최근 글

티스토리

반응형
hELLO · Designed By 정상우.
코락 CoRock

코딩하는 락스타

languages/java

[Java] 이칙연산 계산기 구현

2018. 3. 20. 01:38
반응형

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
 
public class Test2 {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("계산할 수식을 입력하세요 : ");
        // ex. "11+22+33+4+5-10";    result = 65;
        String exp = sc.nextLine();
 
        int plusSum = 0;
        int minusSum = 0;
        
        String[] operand = exp.split("\\+|\\-");
        Queue<Character> operator = new LinkedList<Character>();
        
        for(int i = 0; i < exp.length(); i++) {
            if(exp.charAt(i) == '+')         { operator.add('+'); continue; }
            else if(exp.charAt(i) == '-')     { operator.add('-'); continue; }
            else                            { continue; }
        }
        
        // 첫번째 피연산자는 바로 넣어줌
        plusSum = Integer.parseInt(operand[0]);
        
        // 두번째 피연산자부터 + 연산인지 - 연산인지 판단
        for(int i = 1; i < operand.length; i++) {
            try {
                char ch = operator.poll();
                if(ch == '+') { plusSum += Integer.parseInt(operand[i]); continue; }
                else if(ch == '-') { minusSum += Integer.parseInt(operand[i]); continue; }
            } catch (NullPointerException e) { break; }
        }
        
        System.out.println("결과 : " + (plusSum - minusSum));
    }
}
Colored by Color Scripter
cs

반응형
저작자표시 비영리 변경금지 (새창열림)
    'languages/java' 카테고리의 다른 글
    • [Java] 배열을 이용한 성적관리 프로그램
    • 180320 복습
    • Method Overriding
    • [Java] Generic And Collection
    코락 CoRock
    코락 CoRock
    A COder dreaming of being a ROCKstar

    티스토리툴바