括号匹配-java代码

Bracket.java


package stack;

public class Bracket {
private String input;

public Bracket(String in) {
// TODO Auto-generated constructor stub
input = in;
}

// 括号匹配函数,思想是遇到左括号时入栈,遇到右括号时,出栈,并且判断是否匹配
public void check() {
int stackSize = input.length();
StackX theStack = new StackX(stackSize);

for (int j = 0; j < stackSize; j++) {// 对于字符串中每个字符串进行判断处理
char ch = input.charAt(j);
switch (ch) {
case '{':
case '[':
case '(':
theStack.push(ch);
break;// 取到的字符为左括号时,入栈
case '}':
case ']':
case ')':// 取到的字符为左括号时
if (!theStack.isEmpty()) {// 首先判断栈是否不为空
char chx = theStack.pop();
if ((ch == '}' && chx != '{') || (ch == ']' && chx != '[')
|| (ch == ')' && chx != '(')// 三种错位的情况,也就是当字符串遇到右括号
) // 而从栈弹出的字符不是对应的左括号
System.out.println("Error:" + ch + " at " + j);
} else {
System.out.println("Error:" + ch + " at " + j);
}
break;
default:
break;

}
}
if (!theStack.isEmpty()) // 处理完所有的字符时,栈中还有括号存在,不匹配
System.out.println("Error:missing right bracket");
}

}


Test.java

package stack;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;


public class Test {

public static void main(String[] args) {

String input;

while (true) {

System.out.println("Enter a string:");

System.out.flush();

input = getString();

if (input.equals(""))

break;

else {

Bracket b=new Bracket(input);

b.check();

}

}

}


public static String getString() {

InputStreamReader read = new InputStreamReader(System.in);

BufferedReader buffer = new BufferedReader(read);

String s = null;

try {

s = buffer.readLine();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return s;

}

}

你可能感兴趣的:(括号匹配-java代码)