拆分字符串Java计算器

时间:2015-10-21 14:42:31

标签: java string split calculator

我有这段代码

错误在关于 - ,*和/ operations的if语句中“对于参数类型,运算符/未定义java.lang.String,java.lang.String”任何人都可以帮助

2 个答案:

答案 0 :(得分:0)

您必须解析每个部分以对它们执行数学运算。您不能对字符串执行此类操作(但您可以使用' +'连接字符串,但不能将sum连接起来)。像这样:

import java.util.Scanner;

public class Calculator {    
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in) ;
        System.out.println("Enter your two numbers and the operation with spaces between e.g 8 9 -");

        String calculation=scan.nextLine();

        String [] parts = calculation.split(" ");

        int part1 = Integer.parseInt(parts[0]);
        int part2 = Integer.parseInt(parts[1]);

        int answer;
        String operation = parts[2];
        switch (operation) {
            case "+":
                answer = part1 + part2;
                break;
            case "-":
                answer = part1 - part2;
                break;
            case "*":
                answer = part1 * part2;
                break;
            case "/":
                answer = part1 / part2;
                break;
            default:
                throw new IllegalStateException("Incorrect operation: " + operation);
        }

        String ans = String.valueOf(answer);
        System.out.println(ans);
    }    
}

如果要打印错误的操作符号,则必须修改程序。首先,我们需要将整数 answer 变量初始化为' 0'并且您需要创建新的布尔变量来标记操作的正确性。

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in) ;
        System.out.println("Enter your two numbers and the operation with spaces between e.g 8 9 -");

        String calculation=scan.nextLine();

        String [] parts = calculation.split(" ");

        int part1 = Integer.parseInt(parts[0]);
        int part2 = Integer.parseInt(parts[1]);

        int answer = 0;
        boolean incorrectOperation = false;
        String operation = parts[2];
        switch (operation) {
            case "+":
                answer = part1 + part2;
                break;
            case "-":
                answer = part1 - part2;
                break;
            case "*":
                answer = part1 * part2;
                break;
            case "/":
                answer = part1 / part2;
                break;
            default:
                incorrectOperation = true;
        }

        String ans;
        if(incorrectOperation) {
            ans = "Incorrect operation: " + operation;
        } else {
            ans = String.valueOf(answer);
        }

        System.out.println(ans);
    }
}

答案 1 :(得分:0)

除了使用Integer.parse()之外,为什么不在你的用例中使用scanner.nextInt()?

    int part1 = scan.nextInt();
    int part2 = scan.nextInt();
    String operation = scan.nextLine().trim();