吃完飯花半個小時寫的 代碼比較簡單的 不做解釋了,呵呵
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
小尋 閱讀(1609)
評論(3) 編輯 收藏 所屬分類:
j2se/j2ee/j2me