Sam Sam - 2 months ago 32
Java Question

English Language Calculator [java]

Create a java program that will do the following:

a) Read three inputs from the keyboard,

• two input numbers each being a single digit (0…9)

• one character representing one of five operations : + (addition), - (subtraction), * (multiplication), / (division), and ^ (exponentiation)

b) output the description of the operation in plain English as well as the numeric results

import java.util.Scanner;

public class EnglishCalc {

public static void main(String[] args)
{
Scanner input = new Scanner(System.in);

System.out.println("Enter first number");
int number1 = input.nextInt();

System.out.println("Enter second number");
int number2 = input.nextInt();

System.out.println("Enter operation: +,-,*,/,^");
String operation = input.next();

int output = 0;

if(number1 < 0 || number1 > 9 || number2 < 0 || number2 > 9) {
System.out.println("Number should be between 0 and 10");
}
else if (operation.equals("+"))
{
output = number1 + number2;
System.out.println("Sum of "+number1+" and "+number2+" is: " +output);
}
else if (operation.equals("-"))
{
output = number1 - number2;
System.out.println("Subtraction of "+number2+" from "+number1+" is: " +output);
}
else if (operation.equals("*"))
{
output = number1 * number2;
System.out.println("Product of "+number1+" and "+number2+" is: " +output);
}
else if (operation.equals("/"))
{
if(number2 == 0) {
System.out.println("You cannot divide by 0");
} else {
output = number1/number2;
System.out.println("Division of "+number1+" by "+number2+" is: " +output);
}
}
else if(operation.equals('^'))
{
output = Math.pow((double)number1 , (double)number2);
System.out.println("Value of "+num1+" raised to power of "+num2+" is: " +output);
} else {
System.out.println("Invalid input");
}
}
}


for pow. i tried casting wont work. and if i dont cast, it wont accept int. must be double.

Answer

Use

s1.equals(s2)

to compare strings, instead of using:

s1 == s2

This happens because == is used to compare object references (if the are the same object), so it doesn't compare the 'contain' of that object, in this case a String.

Edit

To print each number in 'words', you could use an array:

String[] numbers = {"zero", "one", "two", ... };

and then use them as:

System.out.println(numbers[2] + " plus " + numbers[5] + ...);