爪哇国新游记之十九

编程入门 行业动态 更新时间:2024-10-10 04:23:34

<a href=https://www.elefans.com/category/jswz/34/1719778.html style=爪哇国新游记之十九"/>

爪哇国新游记之十九

/*** 辅助类* 用于记载字符和位置**/
class CharPos{char c;int pos;public CharPos(char c,int pos){this.c=c;this.pos=pos;}
}/*** 括号检查类**/
public class BracketChecker{/*** 检查函数* @param str* @return* @throws Exception*/public static boolean check(String str) throws Exception{int length=str.length();Stack<CharPos> stack=new Stack<CharPos>(CharPos.class,length);for(int i=0;i<length;i++){char ch=str.charAt(i);if(ch=='{' || ch=='[' || ch=='('){stack.push(new CharPos(ch,i));}else if(ch==')' || ch==']' || ch=='}'){try{CharPos poped=stack.pop();if( (ch==')' && poped.c !='(') || (ch==']' && poped.c !='[') || (ch=='}' && poped.c !='{')){throw new Exception("位于第"+(i+1)+"位的字符"+ch+"没有对应的匹配项");}}catch(java.lang.ArrayIndexOutOfBoundsException e){throw new Exception("位于第"+(i+1)+"位的字符"+ch+"没有对应的匹配项");}}}StringBuilder sb=new StringBuilder();while(stack.isEmpty()==false){CharPos poped=stack.pop();sb.append("位于第"+(poped.pos+1)+"位的字符"+poped.c+"没有对应的匹配项,");}if(sb.length()>0){throw new Exception(sb.toString());}return true;}public static void main(String[] args) throws Exception{String[] arr={"5+2*(3+3)","{[(2+4)*8]/6}","[()]}","{[(]}","{[](","(((((())))))","((([((())))))","[[[[[]]]]]"};for(String str:arr){try{boolean isOk=BracketChecker.check(str);if(isOk){System.out.println("在字符串"+str+"中大中小括号都是匹配的.");}}catch(Exception e){System.out.println("在字符串"+str+"中,"+e.getMessage());}}}
}

输出:

在字符串5+2*(3+3)中大中小括号都是匹配的.
在字符串{[(2+4)*8]/6}中大中小括号都是匹配的.
在字符串[()]}中,位于第5位的字符}没有对应的匹配项
在字符串{[(]}中,位于第4位的字符]没有对应的匹配项
在字符串{[](中,位于第4位的字符(没有对应的匹配项,位于第1位的字符{没有对应的匹配项,
在字符串(((((())))))中大中小括号都是匹配的.
在字符串((([((())))))中,位于第11位的字符)没有对应的匹配项
在字符串[[[[[]]]]]中大中小括号都是匹配的.













本文转自张昺华-sky博客园博客,原文链接:.html,如需转载请自行联系原作者


更多推荐

爪哇国新游记之十九

本文发布于:2024-03-08 03:57:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1719776.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:爪哇   游记

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!