日期:2014-05-19 浏览次数:20639 次
public static int countString(String s){ int num = 0 ; String[] ss = s.split("[\\+\\-\\*/\\(\\)]") ; if( ss.length>2){ int si = 0 ; if( (si=s.indexOf("("))!=-1){ num = countString(s.substring(si+1 , s.indexOf(")"))); num =countString(s.substring(0 , si)+num + s.substring(s.indexOf(")")+1)); }else if((si=s.replaceAll("[\\*/]", ",").indexOf(","))!= -1 ){ System.out.println(si); int statr = s.substring(0, si).replaceAll("[\\+\\-\\*/\\(\\)]", ",").lastIndexOf(",") ; int end = s.substring( si+1).replaceAll("[\\+\\-\\*/\\(\\)]", ",").indexOf(",") ; num = countString(s.substring(statr==-1?0:statr, end==-1?s.length():end+2)); num =countString(s.substring(0 , statr==-1?0:statr)+num + s.substring(end==-1?s.length():end+2)); }else if((si=s.replaceAll("[\\+\\-]", ",").indexOf(","))!= -1 ){ int statr = s.substring(0, si).replaceAll("[\\+\\-\\*/\\(\\)]", ",").lastIndexOf(",") ; int end = s.substring( si+1).replaceAll("[\\+\\-\\*/\\(\\)]", ",").indexOf(",") ; num = countString(s.substring(statr==-1?0:statr, end==-1?s.length():end+2)); num = countString(s.substring(0 , statr==-1?0:statr)+num + s.substring(end==-1?s.length():end+2)); } }else{ int index =s.replaceAll("[\\+\\-\\*/\\(\\)]", ",").indexOf(",") ; if(index!=-1){ String s2 = s.substring(index,index+1) ; if(s2.equals("*")) num = new Integer(ss[0]) * new Integer(ss[1]) ; if(s2.equals("/")) num = new Integer(ss[0]) / new Integer(ss[1]) ; if(s2.equals("+")) num = new Integer(ss[0]) + new Integer(ss[1]) ; if(s2.equals("-")) num = new Integer(ss[0]) - new Integer(ss[1]) ; }else{ num = new Integer(s) ; } } return num; }
------解决方案--------------------
public static int countString(String s){ System.out.println(s); int num = 0 ; String[] ss = s.split("[\\+\\-\\*/\\(\\)]") ; if( ss.length>2){ int si = 0 ; if( (si=s.indexOf("("))!=-1){ num = countString(s.substring(si+1 , s.indexOf(")"))); num =countString(s.substring(0 , si)+num + s.substring(s.indexOf(")")+1)); }else if((si=s.replaceAll("[\\*/]", ",").indexOf(","))!= -1 ){ int statr = s.substring(0, si).replaceAll("[\\+\\-\\*/\\(\\)]", ",").lastIndexOf(",") ; System.out.println(si); int end = s.substring( si+1).replaceAll("[\\+\\-\\*/\\(\\)]", ",").indexOf(",") ; num = countString(s.substring(statr==-1?0:statr+1, end==-1?s.length():si+end+1)); num =countString(s.substring(0 , statr==-1?0:statr+1)+num + s.substring(end==-1?s.length():si+end+1)); }else if((si=s.replaceAll("[\\+\\-]", ",").indexOf(","))!= -1 ){ if(si==0){ num = countString("&"+s.substring(1) ); }else{ int statr = s.substring(0, si).replaceAll("[\\+\\-\\*/\\(\\)]", ",").lastIndexOf(",") ; int end = s.substring( si+1).replaceAll("[\\+\\-\\*/\\(\\)]", ",").indexOf(",") ; num = countString(s.substring(statr==-1?0:s