static List<String> openingBrackets = new ArrayList<String>();
static List<String> closingBrackets = new ArrayList<String>();
public static final String quit = ""; // to be used in sentinel loop
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
// list containing all the opening brackets
openingBrackets.add("(");
openingBrackets.add("{");
openingBrackets.add("[");
openingBrackets.add("<");
System.out.println(openingBrackets);
// list that contains the closing brackets
closingBrackets.add(")");
closingBrackets.add("}");
closingBrackets.add("]");
closingBrackets.add(">");
System.out.println(closingBrackets);
String sent = "value"; // some dummy value assigned to sent.
// creating a stack to store the opening brackets
Stack stackOpening = new Stack();
// creating a stack to store the closing brackets
Stack stackClosing = new Stack();
while (!sent.equals(quit))
{
System.out.println("Enter a string to test:");
sent = scanner.nextLine();
for (int i=0; i<sent.length(); i++)
{
char c = sent.charAt(i);
if (! openingBrackets.contains(c))
{
// push the opening brackets in the String sent
// in the Stack for opening brackets
stackOpening.push(c);
}
if (! closingBrackets.contains(c))
{
// push only the closing brackets in the String
// in the stack for closing brackets
stackClosing.push(c);
}
}
}
}
}
示例输入:
(< [ { } ( { > ) ] >
示例输出:
[ (, <, [, {, }, (, { ]
[ >, ), ], > ]
但是,分别打印两个堆栈时;输出 s
[ (, <, [, {, }, (, {, >, ), ], > ]
答案 0 :(得分:0)
openingBrackets
和closingBrackets
是String
的{{3}}个。但是,如果这些集合包含Collection
s:
char c = sent.charAt(i);
if (! openingBrackets.contains(c))
由于Collection
不包含任何Character
,因此未找到任何匹配项,这就是为什么所有元素都会添加到Stack
s。
要解决此问题,请先测试openingBrackets
的{{1}}和closingBrackets
Collection
,或在测试前将Character
转换为c
,如果它包含在其中一个String
中。
(大多数Collection
检查,如果它们使用Character
方法包含元素,Collection
和String
仅返回Character
,如果两个实例属于同一类型)