我做错了什么。我的运算符 operation 已经是一个字符串。
javac Arithmetic2.java
Arithmetic2.java:44: error: incompatible types: char cannot be converted to String
case '+' : { result = add; }
^
Arithmetic2.java:45: error: incompatible types: char cannot be converted to String
case '-' : { result = sub; }
^
Arithmetic2.java:46: error: incompatible types: char cannot be converted to String
case '*' : { result = mul; }
^
Arithmetic2.java:47: error: incompatible types: char cannot be converted to String
case '/' : { result = div; }
^
Arithmetic2.java:48: error: incompatible types: char cannot be converted to String
case '%' : { result = per; }
^
5 errors
算术2.java
// Arithmetic2.java - This program performs arithmetic, ( +. -, *. /, % ) on two numbers
// Input: Interactive.
// Output: Result of arithmetic operation
import javax.swing.*;
public class Arithmetic2
{
public static void main(String args[])
{
double numberOne, numberTwo;
String numberOneString, numberTwoString;
String operation;
double result;
numberOneString = JOptionPane.showInputDialog("Enter the first number: ");
numberOne = Double.parseDouble(numberOneString);
numberTwoString = JOptionPane.showInputDialog("Enter the second number: ");
numberTwo = Double.parseDouble(numberTwoString);
operation = JOptionPane.showInputDialog("Enter an operator (+.-.*,/,%): ");
// Call performOperation method here
performOperation(numberOne, numberTwo, operation, result);
System.out.format("%.2f",numberOne);
System.out.print(" " + operation + " ");
System.out.format("%.2f", numberTwo);
System.out.print(" = ");
System.out.format("%.2f", result);
System.exit(0);
} // End of main() method.
// Write performOperation method here.
public static double performOperation(double numberOne, double numberTwo, String operation, double result) {
double add = numberOne+numberTwo;
double sub = numberOne-numberTwo;
double mul = numberOne*numberTwo;
double div = numberOne/numberTwo;
double per = numberOne%numberTwo;
switch(operation) {
case '+' : { result = add; }
case '-' : { result = sub; }
case '*' : { result = mul; }
case '/' : { result = div; }
case '%' : { result = per; }
default : { System.out.println("Invalid operator!"); }
}
}
} // End of Arithmetic2 class.
最佳答案
自 JOptionPane::showInputDialog在大多数情况下返回 String
(除了 one 需要大量参数来帮助它返回正确的对象类型),最好在后续流程中使用 String
.
只需将 switch
案例引号从 ''
(char) 更改为 ""
(String)。您无需更改方法参数。
switch(operation) {
case "+" : { result = add; break; }
case "-" : { result = sub; break; }
case "*" : { result = mul; break; }
case "/" : { result = div; break; }
case "%" : { result = per; break; }
default : { System.out.println("Invalid operator!"); break; }
}
编辑:不要忘记 break
s。
关于java - 错误 : incompatible types: char cannot be converted to String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50108980/