사칙연산 계산기입니다. 현재 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

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

 

SimpleDateFormat을 사용해서 자료형 변환 예시입니다.

    /* 포맷만 바꿔서 사용 
        yyyy-MM-dd
        yyyy/MM/dd
   */
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public String date2String(Date date)
    {
        return sdf.format(date);
    }
    
    public Date String2Date(String date) throws ParseException
    {
        return  sdf.parse(date);
    }




내부 내용에 따라 년도, 월, 일만 사용할수도 있고 

yyyy-MM-dd, yyyy/MM/dd yy-MM-dd 등등 원하는 방식으로 사용 가능합니다.

코딩하다 보면 반올림 쓰는경우가 종종 있어서 올립니다.

    public double round(double num, int n)
    {
       double pow = Math.pow(10, n); 
       double result = (double)Math.round(num*pow)/pow;
       return result;
    }

round(3.32231,2);

결과값 3.2

+ Recent posts