2016-09-25 11 views
0

例如: 如果輸入是(5 * x)將返回的結果是: 「括號正確放置」如何確定密文表達式中第一個冗餘括號的索引?

如果輸入是(((5 * x)將返回的結果是: 「括號被置於不正確冗餘開括號的」 「數量:3」

如果輸入是(5 * X)+ 10 * Y)+ 5 * z)的我的返回結果必須是: 「括號放置不當」 「第一個冗餘右括號索引:10」 - 這是我不明白該怎麼辦.................

如何實現一個輸出,該輸出顯示第一個重複右括號的索引?

這是我的代碼:

public static void main(String[] args) { 

    System.out.println("Enter an arithmetic expression:"); 

    Scanner in = new Scanner(System.in); 
    String arithmeticExpression = in.nextLine(); 

    System.out.println(parenthesesCheckup(arithmeticExpression)); 

} 

public static String parenthesesCheckup(String arithmeticExpression) { 

    char openingParenthesis = '('; 
    char closingParenthesis = ')'; 

    Stack<Character> stack = new Stack<Character>(); 

    char array[] = arithmeticExpression.toCharArray(); 

    for (char current : array) { 
     if ((current == closingParenthesis) && stack.empty()) { 
      stack.push(current); 
      char previousStack = stack.peek(); 
      switch (current) { 
       case ')': 
        if (previousStack == '(') 
       stack.pop(); 
       return "Parentheses are placed incorrectly\n" + 
         "Index of first redundant closing parenthesis: "; 
      } 
     } 

     if (current == openingParenthesis) { 
      stack.push(current); 
     } 

     if ((current == closingParenthesis) && !stack.empty()) { 
      char previousStack = stack.peek(); 
      switch (current) { 
       case ')': 
        if (previousStack == '(') 
         stack.pop(); 
        break; 
      } 
     } 
    } 
    if (stack.empty()) { 
     return "Parentheses are placed correctly"; 
    } else { 
     return "Parentheses are placed incorrectly\n" + 
       "Quantity of redundant opening parenthesis: " + stack.size(); 
    } 
} 

}

+0

什麼預計會出現這樣的輸入:'5 + 3)+(2 + 1'? – SergeyS

+0

這看起來像一個「請爲我做功課」的問題。請考慮本指南在SO上編寫一個好問題:https:// codeblog .jonskeet.uk/2012/11/24/stack-overflow-question-checklist/ –

+0

@SergeyS,這樣的輸入不是預期的:) –

回答

0

如何實現的輸出,顯示第一冗餘右括號的指標?

爲您已處理的字符索引添加一個計數器。 例如,你可以轉換for-each循環來計數循環:

for (int index = 0; index < array.length; index++) { 
    char current = array[index]; 
    // ... 

然後當你發現一個不折不扣的地方右括號,目前指數追加到您的字符串:

return "Parentheses are placed incorrectly\n" + 
      "Index of first redundant closing parenthesis: " + index; 
+0

謝謝。有用! –

相關問題