Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何计算运算符和操作数的字符串组合_Java - Fatal编程技术网

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

Java 如何计算运算符和操作数的字符串组合,java,Java,在中间遇到操作员时会出现错误。我知道操作员不能进入 转换为int或其他格式。我正在使用运算符进行计算,方法是读取字节码并将其传递给已定义的枚举。但由于我的字符串具有运算符,因此我在处理这些运算符时遇到了问题。请在这方面帮助我。 ----我的输入是1+2 ----预期产出——1+2=3--- 第--b=Integer.parseInt(st.nextToken())行出错 --执行中的错误----- 进入系列-- 1+2 no of tokens:3 yo 1 go 1 available by

在中间遇到操作员时会出现错误。我知道操作员不能进入
转换为int或其他格式。我正在使用运算符进行计算,方法是读取字节码并将其传递给已定义的枚举。但由于我的字符串具有运算符,因此我在处理这些运算符时遇到了问题。请在这方面帮助我。 ----我的输入是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中的输入,而不是处理它,因此rmeove该s变量及其引用的位置
  • 定义
    字符串行变量修改和更新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!");
}

我已经测试过了,效果很好。

欢迎使用SO。请正确设置您的问题和代码的格式。我正在使用下面的字符串s变量,将其传递给stringtokenizer。运算符和操作数(即运算符=字符(标记))之间的区别是什么?这正是我的问题。您正在接受像a+b这样的参数。所以a是第一个标记,是操作数1,+是另一个标记,是运算符,b是最终标记,是运算符operand2@MohitDarmwal没问题。考虑把它标记为接受,所以当其他人发现这个问题时,他们知道该怎么做。