有没有办法让这个方法运行两次以上

时间:2021-06-17 13:11:08

标签: java methods

我被要求编写一个简单的计算器,只要用户在被问到“是否要执行另一个操作”时输入“是”,它就可以运行多次。 所以我使用了一个单独的方法,该方法将在主方法的循环中使用,问题是如果答案是肯定的,它不会运行超过两次

import java.util.Scanner;

public class Calc2 {
    // method to be called

    static String calcmethod() {
        @SuppressWarnings("resource")
        Scanner Operation = new Scanner(System.in);
        System.out.println("choose operation to perform");
        float x, y, sum, sub, mul, div;
        String g;

        g = Operation.nextLine();
        if (g.equals("addition")) {
            System.out.println("input the first number ");
            x = Operation.nextFloat();
            System.out.println("input the second number ");
            y = Operation.nextFloat();
            sum = x + y;
            System.out.print(sum + "\n");
        } else if (g.equals("subtraction")) {
            System.out.println("input the first number ");
            x = Operation.nextFloat();
            System.out.println("input the second number ");
            y = Operation.nextFloat();
            sub = x - y;
            System.out.print(sub);
        } else if (g.equals("multiplication")) {
            System.out.println("input the first number ");
            x = Operation.nextFloat();
            System.out.println("input the second number ");
            y = Operation.nextFloat();
            mul = x * y;
            System.out.print(mul);
        } else if (g.equals("division")) {
            System.out.println("input the first number ");
            x = Operation.nextFloat();
            System.out.println("input the second number ");
            y = Operation.nextFloat();
            div = x / y;
            System.out.print(div);
        } else {
            System.out.println("invalid input \n");
        }
        System.out.println("would you like to peform another operation \n");
        Scanner Flow = new Scanner(System.in);
        String w;
        w = Flow.nextLine();
        return w;
    }

    public static void main(String[] args) {
        String z = calcmethod();
        if (z.equals("yes")) {
            calcmethod();
        } else {
            System.out.println("end of program");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

使用 do-while 循环,如下例所示:

    public static void main(String[] args) {
        String z = "";
        do {
            z = calcmethod();
        } while(z.equals("yes"));

        System.out.println("end of program");
    }