java将四种方法组合为一种
如何将四个方法替换为将变量“str”更新为将运算符“+-/*”与“ADD、SUB、DIV或MULT”匹配的方法?当它运行case语句时,我试图找出如何让case语句识别通过scanner输入选择的运算符,并将其与相应的描述符字符串相匹配
import java.util.Scanner;
public class Testor4 {
public static void main(String[] args) {
String s1 = getInput("Enter a number: ");
String s2 = getInput("Enter second number");
String op = getInput("Enter operator: + - / * ");
double result = 0;
String str = " You chose to";
try{
switch(op){
case "+": str += getOpNameAdd(str); result = getSum(s1,s2); break;
case "-": str += getOpNameSub(str); result = getSub(s1,s2); break;
case "/": str += getOpNameDiv(str); result = getDiv(s1,s2); break;
case "*": str += getOpNameMult(str); result = getMult(s1,s2); break;
default: System.out.println("not an operator."); return;
}
}catch(Exception e){
System.out.println(e.getMessage());
}
System.out.printf("%s%s%.2f","Result is: ",str,result);
}
private static double getSum(String s1, String s2){
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
return d1 + d2;
}
private static double getSub(String s1, String s2){
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
return d1 - d2;
}
private static double getDiv(String s1, String s2){
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
return d1 / d2;
}
private static double getMult(String s1, String s2){
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
return d1 * d2;
}
public static String getOpNameAdd(String str){
return str = " ADD!";
}
public static String getOpNameSub(String str){
return str = " Subtract!";
}
public static String getOpNameDiv(String str){
return str = " Divide!";
}
public static String getOpNameMult(String str){
return str = " Multiply!";
}
public static String getInput(String prompt){
System.out.println(prompt);
Scanner sc = new Scanner(System.in);
return sc.nextLine();
}
}
# 1 楼答案
使用一种更简单的方法,您可以读取一个输入并处理字符串“前缀+后缀”,其中+表示所有可能的操作, 用类似 static int indexOfAny(String str, char[] searchChars)的东西 获取子字符串前缀、后缀,然后根据运算符切换(op)
# 2 楼答案
为什么不这样做呢
如果字符串将在其他地方重复使用,也可以将其设置为字符串常量:
# 3 楼答案
首先,我要编写一个
enum
(比如这里的Operation
)来封装行为、名称和符号。大概请不要为每个提示打开新的扫描仪。我将把它传递到方法中。像
然后您的
main
方法非常简单,在类似Operation
的# 4 楼答案
我会这样做的。从一个界面开始:
添加的实施:
这是测试仪:
# 5 楼答案
}