计算器使用结果的循环

时间:2019-02-27 12:43:57

标签: java loops calculator

我正在尝试仅从用户那里获得一个输入,并使用先前的结果进行计算。计算器从0开始,尽管我知道乘法可能存在一些问题。目前,这并不重要。我已经坚持了一段时间,但似乎找不到解决方案。所以这看起来像这样:

0
+ 3 (user input)
3 (result)
- 2 (user input)
1 (result)

代码执行了几次,但是我需要某种方式的循环,直到用户说出exite之类的东西为止。

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        System.out.println("Please enter your calculation");
        Scanner scanner = new Scanner(System.in);
        System.out.println("0");
        //int left = scanner.nextInt();
        String op = scanner.next();
        int right = scanner.nextInt();
        int num3 = compute(0,op,right);
        System.out.println(num3);
        int rright;
        int rrright;
        System.out.println("Enter your calculation");
        String op1 = scanner.next();
        rright = scanner.nextInt();
        int num4 = compute(num3,op1,rright);
        System.out.println(num4);
        System.out.println("Enter your calculation");
        String op2 = scanner.next();
        rrright = scanner.nextInt();
        int num5 = compute(num4,op2,rrright);
        System.out.println(num5);
    }

    private static int compute(int left, String op, int right) {
        switch (op.charAt(0)) {
            case '+':
                return left + right;
            case '-':
                return left - right;
            case '*':
                return left * right;
            case '/':
                return left / right;
        }
        throw new IllegalArgumentException("Unknown operator:" + op);
    }
}

1 个答案:

答案 0 :(得分:0)

应该执行SELECT player_id as playerID, SUM('scores') as scores FROM `player_games` GROUP BY player_id ORDER BY SUM('scores') DESC 循环。另外,您应该使用double而不是int,以便正确计算除法的结果(如Lino在其评论中建议的那样)。 代码如下:

while

注意:public static void main(String[] args) { System.out.println("Please enter your calculation"); Scanner scanner = new Scanner(System.in); System.out.println("0"); double result = 0, right; String op; while(true){ System.out.println("Enter your calculation"); op = scanner.next(); if(op.equals("exit")) break; right = scanner.nextDouble(); result = compute(result, op, right); System.out.println(result); } System.out.println("end of program"); } private static double compute(double left, String op, double right) { switch (op.charAt(0)) { case '+': return left + right; case '-': return left - right; case '*': return left * right; case '/': return left / right; } throw new IllegalArgumentException("Unknown operator:" + op); } 期望用逗号分隔的数字(例如4,8)。