你好,Stackoverflow,
我正在为后缀计算器创建中缀。计算器必须从文件中读取输入,然后使用堆栈和队列来创建后缀符号。我有我所有的代码来读取文件并在队列中创建后缀符号。我正在读取的文件包含:
(4>3)+(3=4)+2
这是我在队列中放入后缀符号的代码:
import java.io.*;
import java.util.ArrayList;
public class Proj1Main {
public static void main(String[] args) {
readMathFile();
q.printQueue();
}
public static void readMath(char c, myStack s, myQueue q) {
if (c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9') {
System.out.println("NUMBER"); // <--for testing.
int o = (int)c;
q.enqueue(o);
} else if(c == '+' || c=='-') {
System.out.println("+ or -");
Object x = s.pop();
while( !s.isEmpty() ) {
q.enqueue(x);
x = s.pop();
}
} else if(c == '(' || c == ')' || c == '!' || c == '<' || c == '>' || c == '&' || c == '|' || c == '=') {
System.out.println("other operator"); // <--for testing.
Object x = s.pop();
char y = x.toString().charAt(0);
while( !s.isEmpty() && (y != '\\' || y != '*') ) {
q.enqueue(y);
y = (Character)s.pop();
if(y != '\\' || y != '*') {
q.enqueue(y);
s.push(x);
}
}
} else if(c=='\\' || c == '*') {
System.out.println("divide or multiply"); // <--for testing.
Object x = s.pop();
while( !s.isEmpty() ) {
q.enqueue(x);
x = s.pop();
}
} else if(c == ')') {
System.out.println("close paren"); // <--for testing.
Object x = s.pop();
while( !s.isEmpty() && x != "(" ) {
q.enqueue(x);
x = s.pop();
}
}
}
public static myStack s;
public static myQueue q;
// the file reading code was borrowed from:
// http://www.java2s.com/Code/Java/File-Input-Output/Readfilecharacterbycharacter.htm
public static void readMathFile() {
s = new myStack();
q = new myQueue();
File file = new File("test.txt");
if (!file.exists()) {
System.out.println(file + " does not exist.");
return;
}
if (!(file.isFile() && file.canRead())) {
System.out.println(file.getName() + " cannot be read from.");
return;
}
try {
FileInputStream fis = new FileInputStream(file);
char current;
// in this while loop is where all of the reading happens
while (fis.available() > 0) {
current = (char) fis.read();
readMath(current, s, q);
}
if(fis.available() == 0) {
Object x = s.pop();
while(!x.equals("empty stack"))
q.enqueue(s.pop());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行代码后,我打印输出结果是:
排队:52 51 51 52 50
我不知道 52、51 等是从哪里来的。它应该是“4>33=4+2+”(我想)我想知道是否有人能找出我的问题?或者给我一些关于如何解决它的提示?