我这里有一个简单的计算器,带有一个switch语句,允许用户输入一个字符串,如下所示: * 5
运营商可以是 - + /或* 代码在添加期间正确执行,但是,当我减去一个值时,它会添加它,并且除以或乘以将导致下面列出的例外。
Enter an operator and a number:
+5
Enter an operator and a number:
*2
Exception in thread "main" java.lang.NumberFormatException: For input string: "*2"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at Calculator.whatOperator(Calculator.java:38)
at Calculator.aResult(Calculator.java:29)
at Main.main(Main.java:30)
我相信我没有正确解析双重因为某些原因但我不确定如何这样做...我在想stringtokenizer但是如何在没有分隔符的情况下使用tokenizer? 这是我的计算器课程,下面是我的主要课程
import java.util.Scanner;
public class Calculator {
private final int RESET = 0;
private double number = 0;
private double result = 0;
private char operator;
private Scanner keyboard = new Scanner(System.in);
public Calculator(double number)
{
this.number = number;
}
public void reset()
{
this.number = RESET;
}
public double aResult(Calculator other)
{
other.whatOperator();
this.result = other.result;
return result;
}
public void whatOperator()
{
String operatorString = enterNumber();
// the error occurs here....is there a better way to do this?
double theNumber = Double.parseDouble(operatorString);
char theOperator = operatorString.charAt(0);
this.operator = theOperator;
operatorString ="";
operatorString += theOperator;
// the switch should perform the operation
switch(operatorString){
case "*":
result = getNumber() * theNumber;
break;
case "/":
result = getNumber() / theNumber;
break;
case "+":
result = getNumber() + theNumber;
break;
case "-":
result = getNumber() - theNumber;
break;
case "R":
result = RESET;
break;
case "P":
System.out.println("Goodbye");
System.exit(0);
}
}
public double add(double secondNumber)
{
result = number + secondNumber;
return result;
}
public double divide(double secondNumber)
{
result = number / secondNumber;
return result;
}
public double multiply(double secondNumber)
{
result = number * secondNumber;
return result;
}
public void subtract(double secondNumber)
{
result = number - secondNumber;
}
public double getNumber()
{
return number;
}
public void setNumber(double number)
{
this.number = number;
}
public String enterNumber()
{
System.out.println("Enter an operator and a number:");
String toString = keyboard.nextLine();
return toString;
}
}
public class Main {
public static void main (String[] args) {
Calculator a = new Calculator(0);
a.setNumber(a.aResult(a));
a.setNumber(a.aResult(a));
String theString = String.valueOf(a.getNumber());
System.out.println(theString);
}
}
答案 0 :(得分:1)
这一行错了:
double theNumber = Double.parseDouble(operatorString);
因为它将操作符解析为数字的一部分。相反,使用这个:
double theNumber = Double.parseDouble(operatorString.substring(1));