我正在使用带有各种中缀表达式的输入文件,计算它们,并将它们打印回另一个输出文件,每行格式为:
%%%%% IS%
的模数10值输出文本和模10答案都是正确的;但是,我无法让程序在'#34; OF"之间重新打印整个表达式。和" IS。"
我尝试将output.write(token)
放在getToken()方法中,但我得到了一个"找不到符号"错误。所以我理解我无法从另一个方法访问BufferedWriter,因为它是在main中声明的,但我怎么能解决这个问题呢?
import java.io.*;
public class Lab1
{
public static char token;
public static String expr;
public static int k = 0;
public static void main (String[] args)
{
int exprValue;
String line;
try
{
BufferedReader input = new BufferedReader(new FileReader("inputfile.txt"));
BufferedWriter output = new BufferedWriter(new FileWriter("outputfile.txt"));
while ((line = input.readLine()) != null)
{
output.write("THE MODULO 10 VALUE OF ");
expr = line;
getToken();
output.write(token);
exprValue = expression();
output.write(" IS " + exprValue);
output.newLine();
output.newLine();
k = 0;
}
input.close();
output.close();
}
catch (IOException ex)
{
System.err.println("Exception:" + ex);
}
}
public static void getToken()
{
k++;
int count = k-1;
if(count < expr.length())
{
token = expr.charAt(count);
}
}
public static int expression()
{
int termValue;
int exprValue;
exprValue = term();
while(token == '+')
{
getToken();
termValue = term();
exprValue = (exprValue + termValue)%10;
}
return exprValue;
}
public static int factor()
{
int factorValue = token;
if(Character.isDigit(token))
{
factorValue = Character.getNumericValue(token);
getToken();
}
else if(token == '(')
{
getToken();
factorValue = expression();
if(token == ')')
{
getToken();
}
}
return factorValue;
}
public static int term()
{
int factorValue;
int termValue;
termValue = factor();
while(token == '*')
{
getToken();
factorValue = factor();
termValue = (termValue * factorValue)%10;
}
return termValue;
}
}
目前我的输入是:
(3 * 6 + 4)*(4 + 5 * 7)
3 *((4 + 5 *(1 + 6)2))
我的输出是:
模数10的值(IS 8
3 IS 3的模数10值
答案 0 :(得分:0)
解决了这个问题。在main方法的while循环中,将output.write(token)
替换为output.write(expr)