简体   繁体   中英

Java-Using the scanner and passing variable to other methods

I am trying to create a text based calculator. I have a main class and a calc class. The calc class is where everything will happen, and it will be called in the main class. My problem is several variables in my calc class. It is easier to see in code.

    import java.util.Scanner;

public class Calc {
        String op;
    public void operation(String opt){
        System.out.println("What operation would you like to perform?");
        Scanner operation = new Scanner(System.in);
        op = opt;
        String op = operation.toString();
        getOp(op);
    }

    public String getOp(String op){
        return op;
    }

And later on in my code.

public void calculate(){
        operation(op);
        getNums(1,2);
        if(op == "Division"+"division"+"/"){
            double value = 1/2;
            System.out.println("Your answer is"+value);
        }
        if(op == "Multiplication"+"multiplication"+"*"){
            double value = 1*2;
            System.out.println("Your answer is"+value);
        }
        if(op == "Addition"+"addition"+"+"){
            double value = 1+2;
            System.out.println("Your answer is"+value);
        }
        if(op == "Subtraction"+"subtraction"+"-"){
            double value = 1/2;
            System.out.println("Your answer is"+value);
        }

    }

My problem is that I can't seem to set the value of op with the scanner, and I don't know if the value of my numbers (1 and 2) have been set either. Any help is greatly appreciated, thank you.

FWIW, I would use .nextInt instead of .toString . This would ensure it took in a number and then pass it into your store for conditional to take place.

Plus, I think you would be better off using a switch statement on the calculations, in which case you could leave it as .toString or change it to .next and pass in the char or string.

I think like βнɛƨн Ǥʋяʋиɢ's suggestion, you should not call the operation() in your Cal class. if it just prompts user and takes input, it should be in main class. As i don't see the error message so i guess one of the problem you can get is you declare your op variable one and initiate another local variable op in your operate() function to catch the user's input. Another thing is shouldn't your Scanner object call the method nextLine() instead of toString() to catch the user's input. I don't have my comp with me so can't post any code but maybe you can try to modify your code first and post some error message to be clearer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM