Created a simple Java program to add 2 whole numbers (which is not complete yet). I want help specifically on my variable "sum". Command prompt dictates it may have not been initialized,
I defined sum within the "if statements". How else should I define or what am I doing wrong here? Any help is greatly appreciated!
import java.util.Scanner;
public class Calculator {
public static void main(String[] args){
//Objective: Calculate whole numbers to add, subtract, divide and multiply
Scanner kbd1 = new Scanner(System.in);
Scanner kbd2 = new Scanner(System.in);
int num1, num2, sum;
System.out.println("Enter two whole numbers: ");
num1 = kbd1.nextInt();
num2 = kbd2.nextInt();
System.out.println("Now what would you like to do with these numbers? (Please input add, subtract, multiply, or divide)");
Scanner oper = new Scanner(System.in);
String operation;
operation = oper.nextLine();
if (operation == "add" || operation == "Add")
{
sum = num1 + num2;
}
else
if (operation == "subtract" || operation == "Subtract")
{
if (num1 > num2) {
sum = num1 - num2;
} else {
sum = num2 - num1;
}
}
else
if (operation == "multiply" || operation == "Multiply")
{
sum = num1 * num2;
}
else
if (operation == "divide" || operation == "Divide")
{
sum = num1 / num2;
}
System.out.println("The answer is: " + "/n" + sum);
}
}
UPDATE:
Based on Sotirios Delimanolis, getlost, and other answers:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args){
//Objective: Calculate whole numbers to add, subtract, divide and multiply
Scanner kbd1 = new Scanner(System.in);
Scanner kbd2 = new Scanner(System.in);
int num1, num2, sum;
System.out.println("Enter two whole numbers: ");
num1 = kbd1.nextInt();
num2 = kbd2.nextInt();
System.out.println("Now what would you like to do with these numbers? (Please input add, subtract, multiply, or divide)");
Scanner oper = new Scanner(System.in);
String operation;
operation = oper.nextLine();
if (operation.equals("add"))
{
sum = num1 + num2;
}
else
if (operation.equals("subtract"))
{
if (num1 > num2) {
sum = num1 - num2;
} else {
sum = num2 - num1;
}
}
else
if (operation.equals("multiply"))
{
sum = num1 * num2;
}
else
if (operation.equals("divide"))
{
sum = num1 / num2;
}
else
{sum = 0;}
System.out.println("The answer is: " + "/n" + sum);
}
}
This seems to work now, I had to compare Strings rather than to make explicit absolute values from the user input. Thanks guys!