something wrong with calculation code? - java

this code is supposed to recieve two integers and an operation and then calculate the numbers. this is only part of the entire program everything else works but the calculations are wrong. The only correct output that i get when i run the whole thing is the subtraction. Whats wrong with it?
public static double calculate(int operand1, int operand2, char operation)
{
if (operation=='^')
{
return (Math.pow(operand1,operand2));
}
else if(operation=='+')
{
return ((operand1)+(operand2));
}
else if(operation=='-')
{
return (operand1-operand2);
}
else if(operation=='*')
{
return (operand1*operand2);
}
else
{
if (operand2==0)
{
System.out.println("Cant divide by zero");
}
return(operand1/operand2);
}
}
Here is the entire code for the program
import java.util.Scanner;
public class Calculator
{
public static void main(String[] args)
{
printIntro();
Scanner kb = new Scanner(System.in);
String answer = "yes";
while (answer.equals("yes"))
{
System.out.println("Enter your problem");
String fullExpression=kb.nextLine();
fullExpression=fullExpression.replaceAll("\\s","");
int length=fullExpression.length();
char op1=fullExpression.charAt(0);
char op2=fullExpression.charAt(1);
String operation=fullExpression.substring(2,length);
printEnglish(op1,op2,operation);
System.out.println("Type yes to continue");
Scanner kb1 = new Scanner(System.in);
answer=kb1.nextLine();
};
}
/*this methods gets the operands and the operation and
prints the English version: if we call this method
printEnglish(2,3, plus), then this method will output:
Two plus three = 5 */
public static void printEnglish(char op1, char op2, String operation)
{
String resultOp1CharToString=charToString(op1);
String resultOp2CharToString=charToString(op2);
char resultOperationConversion=operationConversion(operation);
double resultCalculate=calculate(op1, op2, resultOperationConversion);
System.out.print(resultOp1CharToString+ operationConversion(operation) + resultOp2CharToString+ "=" + resultCalculate);
/*1. call the method charToString(op1) to convertlish
word for example ‘1’ to one or ‘2’ to two,….
2. call the method operandConversionToNumber(op1) to
get its numeric value. For example if op1 is ‘1’ then
this method call should return the integer value 1
3. call the method operationConversion(operation) to
convert the operation to a mathematical operation. For
example if you call this method with the string plus
then it will return ‘+’
4. finally call the method calculate to get the result
of the operation.*/
}
/*this method prints the numeric version which is 2 *3
=6*/
//public static boolean printNumeric(char op1, char op2, String operation)
//{
/*String resultCharToString=charToString(op1);
String resultCharToString2=charToString(op2);
int resultOperandToNumber=operandConversionToNumber(op1);
int resultOperandToNumber2=operandConversionToNumber(op2);
char resultOperationConversion=operationConversion(operation);
double resultCalculate=calculate(op1, op2, operation); */
//}
/*this method gets a number as a character and returns
its numeric value as an integer. You must use case
statement for this method*/
public static int operandConversiontoNumber(char operand)
{
int numberOperand=0;
switch(operand)
{
case '0':
numberOperand=0;
break;
case '1':
numberOperand=1;
break;
case '2':
numberOperand=2;
break;
case '3':
numberOperand=3;
break;
case '4':
numberOperand=4;
break;
case '5':
numberOperand=5;
break;
case '6':
numberOperand=6;
break;
case '7':
numberOperand=7;
break;
case '8':
numberOperand=8;
break;
case '9':
numberOperand=9;
break;
}
return numberOperand;
}
/*this method gets the operation as a string and
return the equivalent operation in math. For example
if it receives “plus” the it will return ‘+’ */
public static char operationConversion(String s)
{
char operation=0;
if(s.equals("plus"))
{
operation= '+';
}
else if(s.equals("minus"))
{
operation= '-';
}
else if(s.equals("multiply"))
{
operation= '*';
}
else if(s.equals("divide"))
{
operation= '/';
}
else
{
operation= '^';
}
return operation;
}
/*this method recives two numbers and the operation
and returns the result*/
public static double calculate(int operand1, int operand2, char operation)
{
if (operation=='^')
{
return (Math.pow(operand1,operand2));
}
else if(operation=='+')
{
return ((operand1)+(operand2));
}
else if(operation=='-')
{
return (operand1-operand2);
}
else if(operation=='*')
{
return (operand1*operand2);
}
else
{
if (operand2==0)
{
System.out.println("Cant divide by zero");
}
return(operand1/operand2);
}
}
/*this method converst a number character to its
English word for example if this method receives ‘1’
it will return “one” */
public static String charToString(char num)
{
String englishOperand="one";
switch(num)
{
case '0':
englishOperand= "zero";
break;
case '1':
englishOperand="one";
break;
case '2':
englishOperand="two";
break;
case '3':
englishOperand="three";
break;
case '4':
englishOperand= "four";
break;
case '5':
englishOperand= "five";
break;
case '6':
englishOperand= "six";
break;
case '7':
englishOperand= "seven";
break;
case '8':
englishOperand= "eight";
break;
case '9':
englishOperand= "nine";
break;
}
return englishOperand;
}
//this method prints the decription of this program.
public static void printIntro()
{
System.out.println("This program is a calculator, you need to enter two");
System.out.println("single digit numbers and an operation(plus, minus,");
System.out.println("divide, multiply, power) and it outputs its numeric");
System.out.println("and English version. Your operand and operation can be");
System.out.println("separated by space(s) or there could be no spaces");
System.out.println("between them. For example you can enter “23plus” or “2 3 plus”");
}
}
I entered 2 3 plus and i expect 5 but i dont recieve that, but when i enter 2 3 minus i recieve -1

if (operand2==0)
{
System.out.println("Cant divide by zero");
return -1; // some dummy value
}
else
{
return(operand1/operand2);
}

Division will be incorrect as it's doing integer division and you want a double result. It will also throw a divide by zero error because you don't return.
if (operand2 == 0)
{
System.out.println("Cant divide by zero");
return 0; // I guess
}
return (double)operand1 / (double)operand2;
All the rest look like they should work fine.

Related

Is there a way to access switch case from other method?

I'm developing a maths quiz program which will ask the user whether the wanna have Addition, Subtraction, Division or Multiplication quiz. So by using switch case statement can I access the method?
public static void Addition(){
}
public static void Subtraction(){
}
public static void Division(){
}
Public static void Multi(){
}
static void option(){
Scanner input = new Scanner(System.in);
int choice = 0;
System.out.print("Enter your choice: ");
choice = input.nextInt();
switch (choice){
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
default:
break;
}
Proper syntax would be, for example:
switch (choice){
case 1:
Addition();
break;
case 2:
Subtraction();
break;
case 3:
Division();
break;
case 4:
Multi();
break;
default:
break;
}
I would recommend usually naming methods in Java with camelcase
I think you really want something like this:
public static double add(double x, double y){
return x + y;
}
public static double subtract(double x, double y){
...
}
public static void divide(double x, double y){
...
}
public static double multiply(double x, double y){
...
}
public static void main (String[] args ) {
Scanner input = new Scanner(System.in);
int choice = -1;
while (choice != 5) {
System.out.print("1) add, 2) subtract, 3) divide, 4) multiply 5) quit");
int choice = input.nextInt();
// Get x, y, result
switch (choice){
case 1:
result = add(x, y);
break;
case 2:
result = subtract(x, y);
break;
case 3:
result = divide(x, y);
break;
case 4:
result = multiply(x, y);
break;
default:
System.out.println("Exiting program...");
return;
break;
}
}
Note that you should probably leverage the ability to pass a "return value" from functions (methods). Note, too, that methods are usually "camel case" (e.g. "addNumbers()", instead of "Addition()".

Reverse Polish Calculator not returning the correct values

The following code is for a simple calculator that uses Reverse Polish Notation (3 4 + --> 7)
In theory, if the String "what" is set as "3 4 +" it should return 7.
However when I run it it doesn't return anything.
Also if the String is set to "3 4" it returns 4, instead of an error.
If I have evaluate("3 4 +") the method will get stuck on the last catch block.
Any help is welcome!
Calculator is an interface:
public abstract interface Calculator {
public abstract float evaluate(String what)
throws InvalidExpression, EmptyStack;
}
This is the class I am having issues with:
public class RevPolishCalc implements Calculator {
/*
* NumStack is a facade, basically an ArrayList
*/
private NumStack values = new NumStack();
float answer;
public float evaluate(String what) throws InvalidExpression, EmptyStack {
if((what == null) || (what.equals(""))) {
throw new InvalidExpression("String is either empty or null");
}
try {
Scanner input = new Scanner(what);
while(input.hasNext()) {
if(input.hasNextFloat()) {
values.push(input.nextFloat());
} else {
String next = input.next();
//Symbol is an enum {PLUS, MINUS, TIMES, DIVIDE, INVALID}
Symbol nextSymbol;
if(next == "+") {
nextSymbol = Symbol.PLUS;
} else if (next == "-") {
nextSymbol = Symbol.MINUS;
} else if (next == "*") {
nextSymbol = Symbol.TIMES;
} else if(next == "/") {
nextSymbol = Symbol.DIVIDE;
} else {
nextSymbol = Symbol.INVALID;
}
switch(nextSymbol) {
case PLUS:
values.push(values.pop() + values.pop());
case MINUS:
values.push(-values.pop() + values.pop());
case TIMES:
values.push(values.pop() * values.pop());
case DIVIDE:
values.push(values.pop() / values.pop());
case INVALID:
throw new InvalidExpression("Invalid Value");
default:
throw new InvalidExpression("Unknown Value");
}
}
}
input.close();
answer = values.pop();
} catch (InvalidExpression e) {
throw new InvalidExpression("");
}
return answer;
}
}
There are couple of problems with your code:
Wrong way of comparing Strings:
In your code we can see that you use == to compare String, for example in:
if(next == "+") {
nextSymbol = Symbol.PLUS;
} else if ...
You shouldn't really do that. Use equals instead:
if(next.equals("+")) {
nextSymbol = Symbol.PLUS;
} else if ...
Or better - instead of a bunch of if-elses and equals calls, simply use a switch statement!
switch(next) {
case "+":
nextSymbol = Symbol.PLUS;
break;
case "-":
nextSymbol = Symbol.MINUS;
break;
case "*":
nextSymbol = Symbol.TIMES;
break;
case "/":
nextSymbol = Symbol.DIVIDE;
break;
default:
nextSymbol = Symbol.INVALID;
break;
}
Wrong use of switch statement:
Let's take a look at your handling of the next Symbol:
switch(nextSymbol) {
case PLUS:
values.push(values.pop() + values.pop());
case MINUS:
values.push(-values.pop() + values.pop());
case TIMES:
values.push(values.pop() * values.pop());
case DIVIDE:
values.push(values.pop() / values.pop());
case INVALID:
throw new InvalidExpression("Invalid Value");
default:
throw new InvalidExpression("Unknown Value");
}
It will not work as expected, because you are lacking crucial break calls after each case. Simply add them like so:
switch(nextSymbol) {
case PLUS:
values.push(values.pop() + values.pop());
break;
case MINUS:
values.push(-values.pop() + values.pop());
break;
case TIMES:
values.push(values.pop() * values.pop());
break;
case DIVIDE:
values.push(values.pop() / values.pop());
break;
case INVALID:
throw new InvalidExpression("Invalid Value");
default:
throw new InvalidExpression("Unknown Value");
}
And your method will work as expected.
When you compare the string use
if(next.equals("+")) {
nextSymbol = Symbol.PLUS;
} else if (next.equals("-")) {
nextSymbol = Symbol.MINUS;
} else if (next.equals("*")) {
nextSymbol = Symbol.TIMES;
} else if(next.equals("/")) {
nextSymbol = Symbol.DIVIDE;
} else {
nextSymbol = Symbol.INVALID;
}

Converting all letters in the phone number to digits

Im trying to replace each letter with a digit using the international standard letter/number mapping. I got my output to run correctly however, how do get the dashes in the phone number to appear automatically in the output? For example, if I enter 1800Flowers it prints out as 18003569377. How do I get it to print out as 1-800-3569377 without using regular expressions?
import java.util.Scanner;
public class PhoneKeypad {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//while loop keeps the program running until the user enters quit
while (true) {
System.out.println("\nEnter a phone number or quit to exit:");
String phoneNumber = input.next();
if (phoneNumber.equalsIgnoreCase("quit")) {
System.out.print("\nProgrammed by me");
return;
}
//checks if the phone number entered is at least 8 digits
if (phoneNumber.length() < 8) {
System.out.println("Invalid Phone Number");
} else {
System.out.println(getNumber(phoneNumber));
}
}
}
//method converts all letters in the phone number to digits
public static String getNumber(String phoneNumber) {
int keypadNum = 0;
for (int i = 0; i < phoneNumber.length(); i++) {
char letter = phoneNumber.charAt(i);
if (Character.isAlphabetic(letter)) {
letter = Character.toUpperCase(letter);
switch (letter) {
case 'A':
case 'B':
case 'C':
keypadNum = 2;
break;
case 'D':
case 'E':
case 'F':
keypadNum = 3;
break;
case 'G':
case 'H':
case 'I':
keypadNum = 4;
break;
case 'J':
case 'K':
case 'L':
keypadNum = 5;
break;
case 'M':
case 'N':
case 'O':
keypadNum = 6;
break;
case 'P':
case 'Q':
case 'R':
case 'S':
keypadNum = 7;
break;
case 'T':
case 'U':
case 'V':
keypadNum = 8;
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
keypadNum = 9;
break;
default:
System.out.println("Invalid phone number");
}
phoneNumber = phoneNumber.substring(0, i) + keypadNum + phoneNumber.substring(i + 1);
}
}
return phoneNumber;
}
}
Expected Output:
You could use a regular expression with String.replaceAll. Remove the leading one, group the first three digits, the second three digits and the final group of digits. Something like
public static String formatNumber(String phoneNumber) {
if (phoneNumber.startsWith("1")) {
phoneNumber = phoneNumber.substring(1);
}
return phoneNumber.replaceAll("(\\d{3})(\\d{3})(\\d+)", "1-$1-$2-$3");
}
or
public static String formatNumber(String phoneNumber) {
return phoneNumber.replaceAll("1(\\d{3})(\\d{3})(\\d+)", "1-$1-$2-$3");
}
And then call it like
System.out.println(formatNumber(getNumber(phoneNumber)));
I ran it with 1800flowers and got (as expected)
1-800-356-9377
or without regular expressions like
public static String formatNumber(String phoneNumber) {
if (phoneNumber.startsWith("1")) {
phoneNumber = phoneNumber.substring(1);
}
return "1-".concat(phoneNumber.substring(0, 3)) //
.concat("-").concat(phoneNumber.substring(3, 6)) //
.concat("-").concat(phoneNumber.substring(6));
}
Before calling formatNumber, you can remove the dashes to normalize it with something like
public static String removeDashes(String phoneNumber) {
StringBuilder sb = new StringBuilder();
for (char ch : phoneNumber.toCharArray()) {
if (ch != '-') {
sb.append(ch);
}
}
return sb.toString();
}
Then
System.out.println(formatNumber(removeDashes(getNumber(phoneNumber))));

Why doesn't this switch statement work?

I seem to forget something or do something wrong, but what? Ans what to do if I want it to say "too small" if the number is less then 1?
public static String doStuff(int num) {
String number;
switch (num) {
case 1:
number = "one";
break;
case 2:
number = "two";
break;
case 3:
number = "thee";
break;
case 4:
number = "four";
break;
default:
number = "Not a day";
break;
}
return number;
}
Can only refer from c#
but you should do fine with something like this:
default:
if (num < 1)
number= "too small";
else
number= "Not a day";
break;
You can not handle it in the switch block, but need to have a check before that like
public static String doStuff(int num){
String number;
if (num<1) {
return "too small";
}
switch(num){
case 1:
number= "o

Convert Decimal to Hex using Recursive method Java

I need to make a recursive method that converts a decimal into hexadecimal.
I can't use Integer.toHexString.
EDIT:I tried this code but it doesn't work properly
public static String Hexa(String s) {
String result = "";
int n = Integer.parseInt(s);
int remainder = n % 16;
if (n == 0) {
return Integer.toString(0);
} else {
switch (remainder) {
case 10:
result = "A" + result;
break;
case 11:
result = "B" + result;
break;
case 12:
result = "C" + result;
break;
case 13:
result = "D" + result;
break;
case 14:
result = "E" + result;
break;
case 15:
result = "F" + result;
break;
default: result = Integer.toString(n/16) + result; break;
}
System.out.println(result);
return Hexa(Integer.toString(n/16)) + result;
}
}
Edit:
Changed the default case and the if (n == 0) loop return statement and it works beautifully now.
new code:
public static String Hexa(String s) {
String result = "";
int n = Integer.parseInt(s);
int remainder = n % 16;
if (n == 0) {
return "";
} else {
switch (remainder) {
case 10:
result = "A";
break;
case 11:
result = "B";
break;
case 12:
result = "C";
break;
case 13:
result = "D";
break;
case 14:
result = "E";
break;
case 15:
result = "F";
break;
default:
result = remainder + result;
break;
}
return Hexa(Integer.toString(n / 16)) + result;
}
}
The problem is in your default clause:
default: result = Integer.toString(n/16) + result; break;
it should read:
default: result = Integer.toString(remainder) + result; break;
That will make your program return "04D2".
But there are several other corrections you can make:
Stop converting back and forth to String. For example that same line can be just:
default: result = remainder + result; break;
Also, change your parameters time to int. If you do need to receive a String, then make this an auxiliary function and make your main function receive a String.
You don't need that breakat the end of your default
You don't need a switch. Isn't 'F' = 'A' + (15 - 10) ? You can figure out how to make a formula that translates any number in the range [10,15] to its corresponding letter.
Instead of Integer.toString(0) you can use "0" ... but that isn't even necessary, you can use "" to avoid that leading 0 in your output. If your are worried for handling the special case where the whole number is "0" add a special clause.
The code below may help you to solve your problem:
public static String decimalToAnyBase(int num,int base) {
if(num<base) {
return num+"";
}
String result=null;
int rem=num%base;
String str=decimalToAnyBase(num/base, base);
result=str+((rem>=10)? (char)(rem-10+'A')+"":rem);
return result;
}
import java.util.Scanner;
public class Assign01_05
{
static String res;
public static void hex(int num) //125
{
if(num>=0 && num<10)
System.out.print(num);
else if(num>=10 && num<=15)
{
switch(num)
{
case 10:
System.out.print('A');
break;
case 11:
System.out.print('B');
break;
case 12:
System.out.print('C');
break;
case 13:
System.out.print('D');
break;
case 14:
System.out.print('E');
break;
case 15:
System.out.println('F');
break;
}
}
else
{
hex(num/16);
hex(num%16);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Demical number :");
int num=sc.nextInt();
hex(num);
}
}
import java.util.Scanner;
public class Assign01_05
{
static String res;
public static void hex(int num) //125
{
if(num>=0 && num<10)
System.out.print(num);
else if(num>=10 && num<=15)
{
switch(num)
{
case 10:
System.out.print('A');
break;
case 11:
System.out.print('B');
break;
case 12:
System.out.print('C');
break;
case 13:
System.out.print('D');
break;
case 14:
System.out.print('E');
break;
case 15:
System.out.println('F');
break;
}
}
else
{
hex(num/16);
hex(num%16);
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Demical number :");
int num=sc.nextInt();
hex(num);
}
}
import java.util.Scanner;
public class Ques5 {
public static void hex(int n) {
if(n>9&&n<=15) {
System.out.printf("%c",'A'+(n-10));
}
else if(n>=0&&n<=9){
System.out.printf("%d",n);
}
else {
hex(n/16);
hex(n%16);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the decimal number : ");
int i = sc.nextInt();
System.out.println("The hexadecimal number is : ");
hex(i);
sc.close();
}
}
const char hex_string[17] = "0123456789ABCDEF";
void dec_to_hex(long long x){
if(x == 0) return;
dec_to_hex(x/16);
printf("%c",hex_string[x%16]);
}
Same in Java

Categories