关闭。这个问题需要更加突出重点。它目前不接受答案。
**想改进这个问题吗?**通过编辑这篇文章更新这个问题,使它只关注一个问题。
20天前关门了。
改进这个问题
我用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();
}
}
暂无答案!
目前还没有任何答案,快来回答吧!