사칙연산 계산기입니다. 현재 30라인정도로 줄여보았습니다.

괄호 계산은 지원하지 않지만 이중부호 까지는 지원 합니다.

    List<Double> numList = new ArrayList<Double>();
    public double cal(String org){
    	double result = 0;         
    	char orgChar[] = org.replaceAll(" ", "").toCharArray();
        List<Integer> index = new ArrayList<Integer>();
        for (int i = 0; i < orgChar.length; i++){      
            boolean numChk = String.valueOf(orgChar).matches("[0-9.]");              
            boolean numEd = index.size() % 2 == 0 ? true: false; 
            if (!(numChk || numEd)) index.add(i);             
            else if (numChk && (numEd || i == 0)) index.add(i);  
            if (i == orgChar.length - 1) index.add(orgChar.length);         
        }         
        for (int i = 0; i < index.size(); i+=2){
            String opValue = i == 0 ? org.substring(0, index.get(i)) :  org.substring(index.get(i - 1), index.get(i)); 
            int state = (opValue.length() - opValue.replaceAll("-", "").length()) % 2 == 0 ? 1 : -1;            
            double numValue = state * Double.parseDouble(org.substring(index.get(i), index.get(i+1))); 
            if (opValue.contains("*")) numValue *= numList.remove(numList.size() - 1);
            if (opValue.contains("/")) numValue = numList.remove(numList.size() - 1)/numValue  ;   
            numList.add(numValue);         
        }         
        for (int i = 0; i < numList.size(); i++) result += numList.get(i);   
        return result;    
    }

 

 

결과값 = (-4)-(-40)+(-2) =34

잘 나오는 것을 확인해볼수 있습니다.

 

+ Recent posts