Firstly this is not a homework question. I am practicing my knowledge on java. I figured a good way to do this is to write a simple program without help. Unfortunately, my c
In addition to the other answers, your main() method must be static in order to be a program entry point. In main() you will need to construct your own Calculator object, and call methods on that.
operands
and operators
are out of scope for main. You declare local variables in the constructor, so when you exit the ctor they're eligible for GC and gone.
You have compilation errors - 10 of them.
You are asking for the user to type in integers, but you put the statement operands.next();
as the input. Try to keep consistent with your variables and user input, so changing it to operands.nextInt()
would help.
package org.com;
import java.lang.*;
import java.util.*;
public class Calculator
{
private int solution;
private static int x;
private static int y;
private char operators;
public Calculator()
{
solution = 0;
Scanner operators = new Scanner(System.in);
Scanner operands = new Scanner(System.in);
}
public int addition(int x, int y)
{
return x + y;
}
public int subtraction(int x, int y)
{
return x - y;
}
public int multiplication(int x, int y)
{
return x * y;
}
public int division(int x, int y)
{
solution = x / y;
return solution;
}
public void calc(int ops){
x = 4;
System.out.println("operand 2: ");
y = 5;
switch(ops)
{
case(1):
System.out.println(addition(x, y));
// operands.next();
break;
case(2):
System.out.println(subtraction(x, y));
// operands.next();
break;
case(3):
System.out.println(multiplication(x, y));
// operands.next();
break;
case(4):
System.out.println(division(x, y));
// operands.next();
break;
}
}
public static void main (String[] args)
{
System.out.println("What operation? ('+', '-', '*', '/')");
System.out.println(" Enter 1 for Addition");
System.out.println(" Enter 2 for Subtraction");
System.out.println(" Enter 3 for Multiplication");
System.out.println(" Enter 4 for Division");
Calculator calc = new Calculator();
calc.calc(1);
}
}
This will work