首先,我想先说一下我已经阅读了这里所有与之相关的文章,但这仍然无济于事。我的代码适用于某些方程式,但并非全部。我已经更改了||到&&并返回,重新排列了if语句尝试添加额外的“ pop”的顺序,但是我仍然无法在所有给出的示例中使用它。
import java.io.*;
import java.util.*;
public class Driver
{// driver class
public static void main(String[] args)
{//main
String inPutFile = "test.txt"; //file name
String line; //one line of file
String output = "";
String temp = "";
String c = null;
boolean check;
//Instantiate a Stack
LinkedStackClass stack = new LinkedStackClass( );
System.out.println("Opening file....");
try
{//try
//open the input stream
FileReader fRead = new FileReader(inPutFile);
BufferedReader bRead = new BufferedReader (fRead);
//get data
//read in the first line of the file
System.out.println("Reading data, pushing data on Stack....");
line = bRead.readLine();
//initialize a stack to empty
stack.initializeStack( );
//while not yet at the end of the file
while(line != null)
{//while line not empty
System.out.println(line);
for(int i=0;i<line.length();i++)
{//for loop
c = Character.toString(line.charAt(i));
if(line.charAt(i) == '(' )
{
stack.push("(");
}
else if(line.charAt(i) ==')')
{// else if )
temp = stack.peek();
while(!stack.isEmptyStack() && temp != "(" )
{
stack.pop();
output += temp;
if (!stack.isEmptyStack())
temp = stack.peek();
}
if (!stack.isEmptyStack()){
stack.pop();
}
}
else if (line.charAt(i) =='+' || line.charAt(i) =='~')
{
if(stack.isEmptyStack()){
stack.push(c);
}
else
{
temp = stack.peek();
while (!(stack.isEmptyStack() || !temp.equals ('(') || !temp.equals (')')))
{
output += temp;
stack.pop();
}
stack.push(c);
}
}
else if (line.charAt(i) =='*' || line.charAt(i) =='/')
{//else if * /
if(stack.isEmptyStack())
{
stack.push(c);
}
else
{//else
temp = stack.peek();
while ( !stack.isEmptyStack() && !temp.equals ('(') && !temp.equals ('+')&& !temp.equals ('~'))
{
output += stack.peek();
stack.pop();
}// end while
stack.push(c);
}// end else
}// end else if
else{
output += c;
}
}// end for loop
while(!stack.isEmptyStack())
{//while
temp = stack.peek();
if(temp != "(" )
{
stack.pop();
output += temp;
}
} // end while
System.out.println ("output is " + output);
output = "";
line = bRead.readLine();
}//end while line
//close the input file
bRead.close ();
}//end try
catch(IOException exception)
{
System.out.println(exception.getMessage());
}//end catch
}//end main
}//end class
下面有我得到的输出。这还包括代码应该转换的正则方程
Opening file....
Reading data, pushing data on Stack....
A+B~C
output is ABC~+
(A+B)*C
output is AB+C*
(A+B)/(C~D)
output is AB+CD~/
A+((B+C)*(E~F)~G)/(H~I)
output is ABC+(+EF~G~*HI~/
A+B*(C+D)~E/F*G+H
output is AB+CD+E~*F/GH+*