构造函数和对象

时间:2014-10-11 17:50:46

标签: java

所以我刚刚了解了构造函数。我自己编写了这个程序,我想将构造函数合并到这个程序中(因为它可以使用它!)。我也得到null而不是符号类型,但除了程序运行正常(思考也许构造函数可以修复null)。

我目前的主要问题是我不想取出名为“Options”的类(或称它为方法类?)。但是我仍然想使用构造函数来摆脱“选择”和“getOperatives”。

虽然我知道我的“选项”类(它应该是大写的),但只需简单地进入main,因为它只会被使用一次,我专注于理解这些概念而不是它的健壮性(但仍然健壮)。

    //Call objects
    Scanner scan = new Scanner(System.in);
    css cssAccess = new css();
    //Call Variables
    int choice;
    int x,y;
    int total;
    String type;
    String str;

    //Give Choices & Input Choice

    choice = scan.nextInt();

    //Get 2 itmes to operate on

    System.out.println("Please enter two items to operate on");
    x = scan.nextInt();
    y = scan.nextInt();

    //Pass in operatives AND then choice
    cssAccess.getOperatives(x,y);
    cssAccess.arithmeticDecision(choice);
    //Grab total
    total = cssAccess.answer();
    //Grab type of operation user entered
    type = cssAccess.arithmeticSymbol();
    //Output Results
    System.out.println(x + type + y + " = " + total);

这是包含我所有课程的文件

public class css {


    //Declare Variables
    private int getChoice;
    private int input1,input2;
    private int total;
    private String symbol;
    int refchoice;

     public void choice(int choice){

       getChoice = choice;
    }

    public void getOperatives(int x, int y){
        input1 = x;
        input2 = y;
    }
        public void Options(){
        System.out.println("Would you like to add(1)");
        System.out.println("Would you like to subtract(2)");
        System.out.println("Would you like to multiply(3)");
        System.out.println("Would you like to Divide(4)");
        System.out.println("Or would you like to find the remainder(5)");
    }

    public void arithmeticDecision(int choice){
        choice = refchoice;
        switch (refchoice){
            case 5:total = input1 % input2;
                break;
            case 4:total = input1 / input2;
                break;
            case 3:total = input1 * input2;
                break;
            case 2:total = input1 - input2;
                break;
            case 1:total = input1 + input2;
                break;

        }
    }

    public int answer(){

        return total;
    }

    public String arithmeticSymbol(){
        switch (Integer.toString(refchoice)){
            case "5":symbol = "%";
                break;
            case "4":symbol = "/";
                break;
            case "3":symbol = "*";
                break;
            case "2":symbol = "-";
                break;
            case "1":symbol = "+";
                break;


        }
        return symbol;
    } 
}

0 个答案:

没有答案