繁体   English   中英

如何计算运算符和操作数的字符串混合

[英]How can i calculate a string mix of operators and operands

在两者之间遇到运算符时,它给出错误。我知道运算符不能进入
转换为int或其他格式。我正在使用运算符通过读取字节码并将其传递给定义的enum进行计算。但是由于我的字符串具有运算符,因此我可能会处理这些运算符。 ----我的输入是1 + 2 ----预期的输出-1 + 2 = 3 ---

第----行错误= b = Integer.parseInt(st.nextToken());

-执行中出错------输入序列-1 + 2

no of tokens:3
yo
1
go
1
available

byte info:10
.......
Exception in thread "main" java.lang.NumberFormatException: For input string: "+"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:484)
    at java.lang.Integer.parseInt(Integer.java:527)
    at Abc.main(Abc.java:42) 



I am not able to rectify it. Below is my code

import java.io.*;
import java.util.StringTokenizer;

public class Abc{
public static void main(String[] args) throws Exception
{
System.out.println("Hello World");
System.out.println("Enter the series");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
int a=0;
int b=0;
System.out.println(s);
while ((br.readLine()) != null) 
{
StringTokenizer st=new StringTokenizer(s);

while (st.hasMoreTokens())
{
int i=0;
i=st.countTokens();
System.out.println("no of tokens:"+i);
String token = st.nextToken();
System.out.println("yo");
System.out.println(token);
System.out.println("go");


a=Integer.parseInt(token);
System.out.println(a);

 if (st.hasMoreTokens()) // before consuming another token, make sure 
         {
        System.out.println("available");
        byte b1=(byte)br.read();
        System.out.println("byte info:"+b1);
                         // there's one available
                         if (st.hasMoreTokens()){
              System.out.println(".......");
        b = Integer.parseInt(st.nextToken());  
         System.out.println("///////");

System.out.println(a);
System.out.println("reached");
System.out.println(b);
}
if (b1==43)
{
System.out.println("go");
int foo = Integer.parseInt(calculate(operator.ADDITION, a, b));
}
else if (b1==45)
{
int foo = Integer.parseInt(calculate(operator.SUBTRACTION, a, b));
}
else if (b1==42)
{
int foo = Integer.parseInt(calculate(operator.MULTIPLY, a, b));
}
else if (b1==47)
{
int foo = Integer.parseInt(calculate(operator.DIVIDE, a, b));
}

}
}
}
}

public enum operator
{
    ADDITION("+") {
        public int apply(int  x1, int x2) {
            return x1 + x2;
        }
    },
    SUBTRACTION("-") {
         public int apply(int x1, int x2) {
            return x1 - x2;
        }
    },
 MULTIPLY("*") {
         public int apply(int x1, int x2) {
            return x1 * x2;
        }
    },
     DIVIDE("/") {
         public int apply(int x1, int x2) {
            return x1 / x2;
        }
    };

 // You'd include other operators too...
private final String text;

    private operator(String text) {
        this.text = text;
    }

    // Yes, enums *can* have abstract methods. This code compiles...
    public abstract int apply(int x1, int x2);

    public String toString() {
        return text;
    }

}

public static String calculate(operator op, int x1, int x2)
{
    return String.valueOf(op.apply(x1, x2));
}
}

几个问题:

  • 您只要求在字符串s中输入但不对其进行处理,因此请将该变量及其引用的位置删除。
  • 定义一个String line; 变量修改并更新您的while循环为:

    while((line = br.readLine())!= null)

  • 您不需要此行byte b1=(byte)br.read(); 因为它只有换行符,即输入您在输入行时按下的键
  • 您的while循环应为:

     declare operand1, operand2, count as int declare operator as char while tokenizer has more tokens do optional validate String with token count as 3 with middle token as operator. read token if count == 0 then operand1 = int(token) else if count == 1 then operator = char(token) else operand2 = int(token) done 

如果可以做到,那么使用Java的ScriptEngine类来评估用户给定的字符串会容易得多,如下所示:

ScriptEngineManager engine = new ScriptEngineManager();
ScriptEngine javaScript = engine.getEngineByName("JavaScript");

System.out.print("Please enter a mathematical operation: ");
String op = new Scanner(System.in).nextLine();

try {
    Object a = javaScript.eval(op);
    System.out.println("Result: " + a.toString());
} catch (ScriptException ex) {
    System.out.println("Error in the input!");
}

我已经对其进行了测试,效果很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM