如何解决用于 n 位数字的 Java 计算器
我用 Java 为计算器编写了这段代码,按照设计,它仅适用于一位数的数字。 它适用于递归。 我试图让它适用于多位数字,但没有成功。 如何更改代码以使其适用于多位数字? 你能给我一些想法吗? 还是代码? 随心所欲。
这是适用于一位数的版本。它假设一个数字后面总是跟着一个
- 算术运算符,即
+
、-
、*
或/
- 一个括号,即
(
或)
- 输入字符串的结尾
import java.io.IOException;
import java.io.InputStream;
public class Calculator {
private int lookAheadToken;
private InputStream inputStream;
public Calculator(InputStream inputStream) throws IOException,ParseError {
this.inputStream = inputStream;
lookAheadToken = inputStream.read();
}
private void consume(int symbol) throws IOException,ParseError {
if (lookAheadToken != symbol) throw new ParseError();
lookAheadToken = inputStream.read();
}
private int evalDigit(int digit) {
return digit - '0';
}
private void goal() throws ParseError,IOException {
int result = expr();
if(lookAheadToken == '\n') {
System.out.println("result = " + result);
}
consume(lookAheadToken);
if(lookAheadToken == -1) return;
goal();
}
private int expr() throws ParseError,IOException {
int result = term();
return rest_expr(result);
}
private int rest_expr(int factor) throws ParseError,IOException {
if(lookAheadToken == '\n' || lookAheadToken == ')' || lookAheadToken == -1 ) return factor;
if(lookAheadToken != '+' && lookAheadToken != '-') throw new ParseError();
char operator = (char)lookAheadToken;
consume(lookAheadToken);
int result = term();
if(operator == '+') {
return rest_expr(factor + result);
}
else if(operator == '-') {
return rest_expr(factor - result);
}
else return factor;
}
private int term() throws ParseError,IOException {
int result = factor();
return rest_term(result);
}
private int rest_term(int factor) throws ParseError,IOException {
if(lookAheadToken == '\n' || lookAheadToken == ')' || lookAheadToken == -1 ) return factor;
if(lookAheadToken == '+' || lookAheadToken == '-') return factor;
if(lookAheadToken != '*' && lookAheadToken != '/') throw new ParseError();
char operator = (char)lookAheadToken;
consume(lookAheadToken);
int result = factor();
if(operator == '*') {
return rest_term(factor * result);
}
else if(operator == '/') {
return rest_term(factor / result);
}
return factor;
}
private int factor() throws ParseError,IOException {
if(lookAheadToken == '(') {
consume(lookAheadToken);
int result = expr();
if(lookAheadToken == ')') {
consume(lookAheadToken);
return result;
}
else throw new ParseError();
}
if(lookAheadToken < '0' || lookAheadToken > '9') throw new ParseError();
int result = evalDigit(lookAheadToken);
consume(lookAheadToken);
return result;
}
public static void main(String[] args) throws IOException,ParseError {
InputStream inputStream = System.in;
Calculator calculator = new Calculator(inputStream);
calculator.goal();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。