选项方法在循环重复时初始使用后显示两次

时间:2016-05-07 09:43:03

标签: java

import java.util.Scanner;

public class Calculator {
    static Scanner userInput = new Scanner(System.in);

    public static void main(String[] args) {
        String userInput1 = "";
        //the do loop so i can go through all the options
        do {
            options();
            userInput1 = userInput.nextLine();
            if(userInput1.equals("add")){
                System.out.println(calcAdd());
            }
            else if (userInput1.equals("subtract")) {
                System.out.println(calcSub());
            }
            else if(userInput1.equals("multiply")){
                System.out.println(calcMult());
            }
            else if(userInput1.equals("divide")){
                System.out.println(calcDiv());
            }
        } while(!userInput1.equals("q"));
    }

    //options for the program
    public static void options(){
        System.out.println("add");
        System.out.println("subtract");
        System.out.println("multiply");
        System.out.println("divide");
        System.out.println("\"q\" to quit");
        System.out.print("What do you want to do: ");
    }

    //addition method
    public static int calcAdd(){
        System.out.print("First number: ");
        int x = userInput.nextInt();
        System.out.print("Second number: ");
        int y = userInput.nextInt();
        int z;
        z = x + y;
        return z;
    }

    //subtraction method
    public static int calcSub(){
        System.out.print("First number: ");
        int x = userInput.nextInt();
        System.out.print("Second number: ");
        int y = userInput.nextInt();
        int z;
        z = x - y;
        return z;
    }

    //multiplication method
    public static int calcMult(){
        System.out.print("First number: ");
        int x = userInput.nextInt();
        System.out.print("Second number: ");
        int y = userInput.nextInt();
        int z;
        z = x * y;
        return z;
    }

    //division method
    public static double calcDiv(){
        System.out.print("First number: ");
        double x = userInput.nextDouble();
        System.out.print("Second number: ");
        double y = userInput.nextDouble();
        double z;
        if (y == 0){
            System.out.println("Sorry you can't do this");
        } else {
            z = x / y;
            return z;
        }
        return 0;
    }
}

0 个答案:

没有答案