吃完饭花半个小时写的 代码比较简单的  不做解释了,呵呵
 a(b(cd)e                 少右括号aa(nn)dd)ff           少左括号ade(ed))d(            括号不匹配(左右括号个数相等,但不成对)(dd(r)e)                  括号匹配
a(b(cd)e                 少右括号aa(nn)dd)ff           少左括号ade(ed))d(            括号不匹配(左右括号个数相等,但不成对)(dd(r)e)                  括号匹配
import java.io.*;
public class MainText {
    
    public static void main(String[] args) {
       
        String str=null;
    
           BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); 
    
           System.out.print("请输入字符串:");
    
           try {
               str = buf.readLine();
    
           } catch (IOException e1) {
        
               e1.printStackTrace();
    
           }
         CheckStr checkstr=new CheckStr();
         checkstr.Check(str);
      }         
    
   }
class CheckStr{
    private boolean bool=true;
    
    public void Check(String str){
        char[] ch=str.toCharArray();
         int i=0;
         int chi=0;
         int chj=0;
         
         while(i<ch.length){
             if(ch[i]=='('){
                 chj++;
             }
             if(ch[i]==')'){
                 chj--;
             }
           i++;     
         }
         i=0;
         
         while(i<ch.length && bool==true){
                      
             while(i<ch.length){
              if(ch[i]=='(' && ch[i]!=')'){
                     chi++;
                 }else if(ch[i]==')'){
                     break;
                 }     
                 i++;
             }
             
             for( ;i<ch.length;i++){
                 if(ch[i]==')' && ch[i]!='('){
                     chi--;
                 }else if(ch[i]=='('){
                     break;
                 }
             }
             
             if(chi!=0){
                 bool=false;
             }
             if(chi>0&&chj!=0){
                 System.out.println("缺少右括号");
                 try {
                     throw new Exception("缺少右括号");
                  } catch (Exception e) {
                     e.printStackTrace();
                  }
             }
             if(chi<0&&chj!=0){
                 System.out.println("缺少左括号");
                 try {
                     throw new Exception("缺少左括号");
                  } catch (Exception e) {
                     e.printStackTrace();
                  }
             }
        }
          
         if(bool==true){
             System.out.println("括号是匹配的");
             try {
                 throw new Exception("括号是匹配的");
              } catch (Exception e) {
                 e.printStackTrace();
              }
         }
         else if(chj==0){
             System.out.println("括号是不匹配的");
             try {
                 throw new Exception("括号是不匹配的");
             } catch (Exception e) {
                 e.printStackTrace();
             }
        }
  } 
}
   地震让大伙知道:居安思危,才是生存之道。
 
 
	posted on 2007-08-21 20:05 
小寻 阅读(1626) 
评论(3)  编辑  收藏  所属分类: 
j2se/j2ee/j2me