How to multiply two integers using two classes, Class one contains method int calculateMultiplication (int, int) and two contains main method?

I need help with this program. I need to multiply the two integers that are inputted by user and then use the method int calculateMultiplication (int, int) to calculate the result. The first class contains the declaration of variables and the methods and the second class contains the main method with all the print. I don’t know how to call the calculateMultiplication method to implement in my final print which gives “The multiplication of first user input (i got) and second user input (i got) is result (i dont have).

public class JavaApplication19 {

    public static void main(String[] args) {
        
    Scanner input = new Scanner (System.in);
    System.out.print("Enter the first int number: ");
    int num1 = input.nextInt();
    Two Num1 = new Two();
    Num1.setN1 (num1);
    int numOne = Num1.getN1();
    
    System.out.print("Enter the second int number: ");
    int num2 = input.nextInt();
    Two Num2 = new Two();
    Num2.setN2 (num2);
    int numTwo = Num2.getN2();  
    }
}  
    
This is the part I need help on: (this is just what i have so far)

    System.out.println("The multiplication of " + numOne + " and " + numTwo + " is" + product + "." );
    Two Result = new Two();
    int result = Result.calculateMultiplication(num1, num2);

class Two {
 
    private int result;
    private int n1;
    private int n2;
    
    public int getN1(){
        return n1;
    }
    
    public void setN1(int _n1){
        n1 = _n1;
    }
    
    public int getN2(){
        return n2;
    }        
    
    public void setN2(int _n2){
        n2 = _n2;
    }
    
    
    public int calculateMultiplication(int n1, int n2){
        int answer = this.n1 * this.n2;
        return result;
    
    }
    
}

Answer

Be careful with instance variables and method parameters.

The two class could be written a bit differently:

public class Two {
    private int n1;
    private int n2;
    private int result;
    public void setN1(int n1) {
        this.n1 = n1;
    }
    public void setN2(int n2) {
        this.n2 = n2;
    }
    public void multiply() {
        this.result = this.n1 * this.n2;
    }
    public int getResult() {
        return this.result;
    }
}

It has two private int instance variables, n1 and n2.

int num1 = 10; // for example
int num2 = 20; // for example

Two two = new Two();
two.setN1(num1);
two.setN2(num2);
two.multiply();
int result = two.getResult();

From here you can do whatever you need with the values.

Leave a Reply

Your email address will not be published. Required fields are marked *