當遇到操作符時發生錯誤。我知道運算符不能轉換爲
轉換後的int或其他格式。我使用運算符通過讀取字節代碼來計算和傳遞給枚舉defined.But作爲我的字符串有運營商,所以我有prob在處理這些。請幫助我這一點。 ---- My Inputs is 1 + 2 ---- Expected Output-- 1 + 2 = 3 ---如何計算運算符和操作數的字符串混合
錯誤行---- b = Integer.parseInt(st.nextToken() );
--error在exceution期間----- 輸入系列 - 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));
}
}
歡迎來到SO。請正確格式化您的問題和您的代碼。 – m0skit0 2014-12-02 09:15:39