如果提示允许用户输入“add 1 2”
如何将此转换为1 + 2并输出答案?
“sub 1 2”相同 到1-2
我知道可以拆分成数组来解决这个问题,但我的老师不会让我们这样做这个任务,我们所允许的只是使用if和for循环。
我对代码的想法如下,但它不会让我通过,因为双i = line.nextDouble()将无法正常工作
import java.util.Scanner;
public class Shell {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to CS302Shell! "
+ "Enter help for a list of commands or exit to end.");
String command = input.next();
String line = input.nextLine();
if (command.equals("add")) {
double i = line.nextDouble();
}
} /** method */
} / ** class * /
答案 0 :(得分:2)
您可以使用split
方法将字符串拆分为正确的部分:
public static double calculate(String input) {
// Here you splitt the input-String at every space. So you get 3 pieces
String[] splitted = input.trim().replace(" +", " ").split(" ");
// Set the different element-values to variables
String operator = splitted[0];
// Here you have to cast the String to double because you can't
// calculate with a String
double first;
double second;
//With this try-catch block you check if the numbers are really numbers.
try {
first = Double.valueOf(splitted[1]);
second = Double.valueOf(splitted[2]);
} catch (NumberFormatException ne) {
System.err.println("Your input for one of the numbers was wrong");
return 0;
}
// Now you check which operator the user wants and return the result.
switch (operator) {
case "add":
return first + second;
case "sub":
return first - second;
case "multiply":
return first * second;
case "divide":
return first / second;
// If de user has given a wrong input, the return is 0
default:
return 0;
}
}
public static void main(String[] args) {
System.out.println(calculate("add 1 2"));
}
答案 1 :(得分:0)
字符串解析:
int result = 0;
String[] data = "add 1 2".split(" ");
switch(data[0]) {
case "add":
int param1 = Integer.parseInt(data[1]);
int param2 = Integer.parseInt(data[2]);
result = param1 + param2;
break;
case "sub":
//...
break;
}
你明白了。
一些数据验证将是一个好主意。
还有一些try / catch阻塞了parseInt调用,以确保当有人输入"添加b"时,程序不会爆炸。等...
答案 2 :(得分:0)
你应该先发布你的尝试,这样我们才能更好地帮助你,但我认为这可能是你想要的。所有这些代码都假设您输入了正确的输入。
public int addInput(String input){
inputs = inputs.replace("add ", "");
String[] inputs = input.split(" ", 2);
return Integer.parseInt(inputs[0])+Integer.parseInt(inputs[1]);
}
public int subInput(String input){
inputs = inputs.replace("sub ", "");
String[] inputs = input.split(" ", 2);
return Integer.parseInt(inputs[0])-Integer.parseInt(inputs[1]);
}
认真地看到你的代码会很好。 :)