2014-03-31 2 views
3

을 사용하여 방정식 :분할까지 내가 좋아 방정식 입력하면 ArrayList에

9+3*2/1 

내 출력은 다음과 같습니다

[9,3,2,1] 
[,+,*,/] 

왜 내 두 번째 배열은 ","어떻게 할로 시작 않습니다 그래서 출력이 될 것이다 그것을 제거

[+,*,/] 
String evaluate(String exp) { 

     String setExpression = expr.getText(); 

     String[] numbers = setExpression.split("[*/+-]"); 
     String[] ops = setExpression.split("[123456789]"); 

     ArrayList <String> setNumbers = new ArrayList <String>(); 
     ArrayList <String> setOps = new ArrayList <String>(); 


     for(int i=0; i<numbers.length; i++){ 
      setNumbers.add(numbers[i]); 
     } 

     for(int i=0; i<numbers.length; i++){ 
      setOps.add(ops[i]); 
     } 

     System.out.println(setNumbers); 
     System.out.println(setOps); 

     return exp; 
    } 
} 
+0

'setOps' 목록에 세 개 또는 네 개의 요소가 있습니까? –

+0

'*'을 (를) 탈출 할 가능성이 있습니까? –

+1

배열은','로 시작하지 않지만 공백 문자열을 가지고 있고 그것은 당신의 split regex에 기인합니다. – qqilihq

답변

0

여분의 빈 문자열은 분할에서 9 이전에 나오는 문자열입니다. 당신은 숫자로 나눠야한다고 말하고 있습니다 - 시작과 끝 부분에 여분의 빈 문자열이있을 것입니다.

마지막에 여분의 빈 문자열이 표시되지 않는 유일한 이유는 분할을 ArrayList에 복사 할 때 numbers.length에 머물러 있기 때문입니다.

숫자가 두 자리 이상인 경우 여기에 빈 문자열이 생깁니다.

3

네 유사한 예 :

public class DemoSplit { 
    public static void main(String[] args) { 
     String s = ",1,2,"; 
     String su[] = s.split(","); 
     for (String st: su) System.out.println("'"+st+"'"); 
    } 
} 

인쇄 것이다

'' 
'1' 
'2' 

첫 문자가 분리되므로이 분할 및 요소는 제 esplitted 어레이의 첫 번째 요소이다 전 . 귀하의 경우에는

당신은 숫자에 spliut :

9+3*2/1 

'+'후, 빈 요소, ... 9 전

당신이 코드를보고 기분이 경우, String.split 전화 java.util.regex.Pattern.split

split 메서드에서 첫 번째 반복에 대한 인덱스가 0이고 예제의 첫 번째 일치 항목이 0이므로 첫 번째 요소는 빈 문자열입니다. 따라서 인덱스와 일치 사이의 하위 문자열을 ArrayList에 추가합니다. 분할 방법의 소스 코드에서 : 난 = 1. 작전의 첫 번째 요소 때문에 당신이 그것을 분할하는 방식의 빈 문자열 그래서

ArrayList<String> matchList = new ArrayList<String>(); 
    Matcher m = matcher(input); 

    // Add segments before each match found 
    while(m.find()) { 
     if (!matchLimited || matchList.size() < limit - 1) { 
      String match = input.subSequence(index, m.start()).toString(); 
      matchList.add(match); 
      index = m.end(); 
     } else if (matchList.size() == limit - 1) { // last one 
      String match = input.subSequence(index, 
              input.length()).toString(); 
      matchList.add(match); 
      index = m.end(); 
     } 
    } 
0

당신은 루프에 대한 두 번째의 시작을 변경할 수 있습니다.

+0

을 참조하십시오. 식의 첫 번째 문자가 '-'기호 인 경우 문제가 될 수 있습니다. –