大家好,我正在尝试创建一个程序以允许用户输入一系列括号(一次一个)并检查是否有相应的结束括号。每次都在新行中输入括号以帮助阅读。我已经为它设置了一个 ADT,但只是想不出如何让 while 循环进行和检查......我知道如果输入了一个(括号我应该把它推入堆栈,当一个(是输入我应该弹出一个堆栈,但我无法计算出中间的位,任何帮助都会受到喜爱:)
//main code
import java.util.*;
public class SameBrackets
{
public static void main(String[] args)
{
Stack bracket = new Stack();
Scanner kybd = new Scanner(System.in);
System.out.print("Enter bracket > ");
String bracketentered = kybd.next();
if ("(".equals(bracketentered) )
{
bracket.push(bracketentered);
System.out.println(") needed");
}
else if (")".equals(bracketentered))
{
bracket.pop();
System.out.println("( needed");
}
}
}
//ADT代码
public class Stack
{
private String[] a; //String array
private int top;
public Stack()
{
a = new String[1]; //create String array
top = 0;
}
public boolean isEmpty()
{
return top == 0;
}
public String pop() //pop String element
{
top--;
return(a[top]); //underflow not protected
}
public void push(String x) //push String element
{
if (top == a.length)
{
resize();
}
a[top] = x;
top++;
}
private void resize()
{
String[] temp = new String[a.length * 2]; //resize String array
for (int i = 0; i < a.length; i++)
{
temp[i] = a[i];
}
a = temp;
}
}