我应该创建一个 Java 程序来读取表达式,其中包含大括号 { }、方括号 [ ] 和圆括号 ( ) 等。我的程序应该正确嵌套,并且 '(' 匹配 ')'、'[' 匹配 ']' 和 '{' 匹配 '}' 程序应该在输入行的开头以 '$' 终止。这些应该是我的程序的示例运行:
Enter an Expression:
A[F + X {Y – 2}]
The expression is Legal
Enter an Expression:
B+[3 – {X/2})*19 + 2/(X – 7)
ERROR—‘]’ expected
Enter an Expression:
()) (
ERROR--‘)’ without ‘(‘
$
我创建了一个名为 BalancedExpression 的类和一个名为 ExpressionChecker 的驱动程序。我完成了我的 BalancedExpression 课程。但是,我在设置驱动程序以使用 InputStreamReader 和 BufferedReader 打印出表达式时遇到问题。我唯一能弄清楚的是如何通过让用户输入 $ 来终止我的程序。
到目前为止,这是我的代码:
平衡表达类:
public class BalancedExpression
{
public BalancedExpression() // Default Constructor
{
sp = 0; // the stack pointer
theStack = new int[MAX_STACK_SIZE];
}
public void push(int value) // Method to push an expression into the stack
{
if (!full())
theStack[sp++] = value;
}
public int pop() // Method to pop an expression out of the stack
{
if (!empty())
return theStack[--sp];
else
return -1;
}
public boolean full() // Method to determine if the stack is full
{
if (sp == MAX_STACK_SIZE)
return true;
else
return false;
}
public boolean empty() // Method to determine if the stack is empty
{
if (sp == 0)
return true;
else
return false;
}
public static boolean checkExpression(String ex) // Method to check Expression in stack
{
BalancedExpression stExpression = new BalancedExpression();
for(int i = 0; i< MAX_STACK_SIZE; i++)
{
char ch = ex.charAt(i);
if(ch == '(' || ch == '{' || ch == '[')
stExpression.push(ch);
else if(ch == ')' && !stExpression.empty() && stExpression.equals('('))
stExpression.pop();
else if(ch == '}' && !stExpression.empty() && stExpression.equals('{'))
stExpression.pop();
else if(ch == ']' && !stExpression.empty() && stExpression.equals('['))
stExpression.pop();
else if(ch == ')' || ch == '}' || ch == ']' )
return false;
}
if(!stExpression.empty())
return false;
return true;
}
private int sp;
private int[] theStack;
private static final int MAX_STACK_SIZE = 6;
}// End of class BalancedExpression
我的驱动程序:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExpressionChecker
{
public static void main(String[] args)
{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader console = new BufferedReader(reader);
BalancedExpression exp = new BalancedExpression();
String expression = "";
do
{
try{
System.out.print("Enter an Expression: ");
expression = console.readLine();
if("$".equals(expression))
break;
}catch(Exception e){
System.out.println("IO error:" + e);
}
}while(!expression.equals(""));// End of while loop
}
}// End of class ExpressionChecker
谁能帮我开发我的驱动程序以打印出类似于示例示例的输出?任何帮助表示赞赏。谢谢!