How can I do one-operand math with my Java calculator? - java

I have been trying to create a simple calculator in Java for a while now, and I have successfully been able to make the program work with two-operand equations (+, -, *, /, and ^). However, I was wondering how I would be able to do one-operand math problems - absolute value(using the symbol "|"), square root (using the symbol 'v'), rounding to the closest integer (using the symbol '~'), sin (s), cos (c), and tangent (t).
I have attempted the absolute value operand which can be seen in:
if (operator == '|') {
answer = Math.abs(numA);
}
// In the main class
and:
double absolute(double a) {
double answer = Math.abs(a);
return answer;
}
// In the maths class
This code only works if you enter in values for example like this: -3 | -3 (Note: I have noticed that it is only the first number that the absolute value operation is performed upon. The second number can be whatever you want (if you entered -3 | -4 your answer would still be 3) as long as it is, indeed, a number.
Any help for solving this problem and help figuring out the other single-operand operations would be greatly appreciated!
Thanks in advance!
The source code for my program is below:
package calculator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
System.out.println("Hello, welcome to my calculator");
System.out.println("Enter in some stuff you want to me to calculate");
Scanner scan = new Scanner(System.in);
System.out.println("If you need help please type \"help\"");
System.out.println("If at anytime you want to leave, type \"quit\"");
System.out.println("Hit enter to continue.");
String s1 = scan.nextLine();
if (s1.equals("help")){
System.out.println(" ");
System.out.println("Double operand commands:");
System.out.println("Addition: '+' (Ex: 'a + b' )");
System.out.println("Subtraction: '-' (Ex: 'a - b' )");
System.out.println("Multiplication: '*' (Ex: 'a * b' ) ");
System.out.println("Division: '/' (Ex: 'a / b' )");
System.out.println("Exponents: '^' (Ex: 'a ^ b' )");
System.out.println(" ");
}
Scanner input = new Scanner(System.in);
Maths maths = new Maths();
double answer = 0;
double numA, numB;
char operator;
boolean quit = false;
while (true) {
System.out.print("Please enter your equation: ");
String s=input.next();
if(s.equals("quit")){
System.out.println("Thank you for using my program!");
System.exit(0);
}
numA = Double.parseDouble(s);
operator = input.next().charAt(0);
numB = input.nextDouble();
if (operator == '+') {
answer = maths.add(numA, numB);
}
if (operator == '-') {
answer = maths.subtract(numA, numB);
}
if (operator == '*') {
answer = maths.multiply(numA, numB);
}
if (operator == '/') {
answer = maths.divide(numA, numB);
}
if (operator == '^') {
answer = maths.power(numA, numB);
}
if (operator == '|') {
answer = Math.abs(numA);
}
System.out.println(answer);
}
}
}
class Maths {
double add(double a, double b) {
double answer = a+b;
return answer;
}
double subtract(double a, double b) {
double answer = a-b;
return answer;
}
double multiply(double a, double b) {
double answer = a*b;
return answer;
}
double divide(double a, double b) {
double answer = a/b;
return answer;
}
double power(double a, double b){
double answer =a;
for (int x=2; x<=b; x++){
answer *= a;
}
return answer;
}
double absolute(double a) {
double answer = Math.abs(a);
return answer;
}
}

I did some modification in your existing code so that it can suit in all cases and allow future extension of functions. You can understand the changes through comments. Also, the code will be able to run, if user provide only one input for functions, where only single parameter is enough. I did not change any of your functions.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
System.out.println("Hello, welcome to my calculator");
System.out.println("Enter in some stuff you want to me to calculate");
Scanner scan = new Scanner(System.in);
System.out.println("If you need help please type \"help\"");
System.out.println("If at anytime you want to leave, type \"quit\"");
System.out.println("Hit enter to continue.");
String s1 = scan.nextLine();
if (s1.equals("help")) {
System.out.println(" ");
System.out.println("Double operand commands:");
System.out.println("Addition: '+' (Ex: 'a + b' )");
System.out.println("Subtraction: '-' (Ex: 'a - b' )");
System.out.println("Multiplication: '*' (Ex: 'a * b' ) ");
System.out.println("Division: '/' (Ex: 'a / b' )");
System.out.println("Exponents: '^' (Ex: 'a ^ b' )");
System.out.println(" ");
} else if (s1.equals("quit")) {
System.out.println("Thank you for using my program!");
System.exit(0);
}
Scanner input = new Scanner(System.in);
Maths maths = new Maths();
double answer = 0;
double numA=0.0, numB=0.0;
char operator;
boolean quit = false;
while (true) {
System.out.print("Please enter your equation: ");
//First scan the function as a string
String s = input.next();
if (s.equals("quit")) {
System.out.println("Thank you for using my program!");
System.exit(0);
}
//We will use regex to find the operator, so we will omit all alphabetic letter or numeric number or decimal
String operator1 = s.replaceAll("[a-zA-Z0-9.]","");
//For functions like -4|, the operator1 will be -| after replacing through regex, we will only take the second digit as operator to prevent error
if(operator1.length()==1)
operator = operator1.charAt(0);
else
operator = operator1.charAt(1);
String[] num11 = (s.split("[^0-9,.]"));
//String array num11 may contain null string after splitting using regex, we will remove those null string and store only variable values in an arraylist
ArrayList<String> arraylist = new ArrayList<String>();
for (int i = 0; i < num11.length; i++)
{
if (!num11[i].equals(""))
{
arraylist.add(num11[i]);
}
}
if(arraylist.size()==1){
numA = Double.parseDouble(arraylist.get(0));
numB=numA;}
else if(arraylist.size()==2){
numA = Double.parseDouble(arraylist.get(0));
numB = Double.parseDouble(arraylist.get(1));
}
if (operator == '+') {
answer = maths.add(numA, numB);
}
if (operator == '-') {
answer = maths.subtract(numA, numB);
}
if (operator == '*') {
answer = maths.multiply(numA, numB);
}
if (operator == '/') {
answer = maths.divide(numA, numB);
}
if (operator == '^') {
answer = maths.power(numA, numB);
}
if (operator == '|') {
answer = Math.abs(numA);
}
System.out.println(answer);
}
}
public static class Maths {
public void Maths(){};
double add(double a, double b) {
double answer = a + b;
return answer;
}
double subtract(double a, double b) {
double answer = a - b;
return answer;
}
double multiply(double a, double b) {
double answer = a * b;
return answer;
}
double divide(double a, double b) {
double answer = a / b;
return answer;
}
double power(double a, double b) {
double answer = a;
for (int x = 2; x <= b; x++) {
answer *= a;
}
return answer;
}
double absolute(double a) {
double answer = Math.abs(a);
return answer;
}
}
}
Output:
Please enter your equation: +4+4
8.0
Please enter your equation: 4+4
8.0
Please enter your equation: 4+3
7.0
Please enter your equation: 4-3
1.0
Please enter your equation: 4/3
1.3333333333333333
Please enter your equation: -4|
4.0
Please enter your equation: 4|
4.0
Please enter your equation: 3^2
9.0

Use a regular expression to check whether first number is actually a number. Then do what you want to do accordingly. Additionally, you can handle erroneous user inputs using regular exceptions. So you won't have java.lang.NumberFormatExceptions if you enter "3+3"
if (s.matches("^[-+]?[0-9]*\\.?[0-9]+$")) { //Check whether first number is actually a number
numA = Double.parseDouble(s);
operator = input.next().charAt(0);
numB = input.nextDouble();
} else {
operator = s.charAt(0);
numA = input.nextDouble();
numB = 0;
}

Related

How to get a looping program in Java

I am new to Java programming and I wanted to try to make a calculator. I made the code, but the only problem is that it will only run once. I was wondering if there was any way to get it to "loop". By that I mean, add a question to go to the beginning of the main method that way I can run the calculator again. Here is the code I have...
import java.util.Scanner;
public class calculatorFull {
public static void main(String[] args){
int op;
double num1, num2;
Scanner operation = new Scanner(System.in);
System.out.println("1 - Add\n2 - Subtract\n3 - Multiply\n4 - Divide");
System.out.print("Which operation would you like to perform? ");
op = operation.nextInt();
if((op != 1) && (op != 2) && (op != 3) && (op != 4)){
System.out.println("That wasn't an option...");
}else{
System.out.print("First number: ");
num1 = operation.nextDouble();
System.out.print("Second number: ");
num2 = operation.nextDouble();
if(op==1){
Add(num1, num2);
}else if(op==2){
Sub(num1, num2);
}else if(op==3){
Mult(num1, num2);
}else if(op==4){
Div(num1, num2);
}
}
}
public static void Add(double x, double y){
double numsum;
numsum = x + y;
System.out.printf("%s + %s = %s", x, y, numsum);
}
public static void Sub(double x, double y){
double numsum;
numsum = x - y;
System.out.printf("%s - %s = %s", x, y, numsum);
}
public static void Mult(double x, double y){
double numsum;
numsum = x * y;
System.out.printf("%s * %s = %s", x, y, numsum);
}
public static void Div(double x, double y){
double numsum;
numsum = x / y;
System.out.printf("%s / %s = %s", x, y, numsum);
}
}
Thanks in advance for the help!
Btw, I think this might be different from this question (User input to repeat program in Java). I have different methods that I call from and that was changed to call from the main to just 1 method. Don't know if that changes any of the solutions or if it is the same problem but thank you for pointing out that it might be.
You can set a sentinel value to exit the program (i.e., -1 in your option) and keep track of a variable that we will constantly check in a while loop. If op ever becomes -1, it exits. Otherwise, it will restart the logic inside the while loop.
int op = 0;
while(op != -1) {
double num1, num2;
Scanner operation = new Scanner(System.in);
System.out.println("1 - Add\n2 - Subtract\n3 - Multiply\n4 - Divide");
System.out.print("Which operation would you like to perform? ");
op = operation.nextInt();
if((op != 1) && (op != 2) && (op != 3) && (op != 4)){
System.out.println("That wasn't an option...");
}else{
System.out.print("First number: ");
num1 = operation.nextDouble();
System.out.print("Second number: ");
num2 = operation.nextDouble();
if(op==1){
Add(num1, num2);
}else if(op==2){
Sub(num1, num2);
}else if(op==3){
Mult(num1, num2);
}else if(op==4){
Div(num1, num2);
}
}
int continue = 0;
while(continue == 0){
// Put your calculator code here
System.out.println("Enter 1 to exit or 0 to continue");
choice = Integer.parseInt(br.readLine());
}
Try this.
UPDATE:
Use this:
import java.io.*;
public class StackOverFlow
{
// arguments are passed using the text field below this editor
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int cont = 0;
while(cont == 0){
System.out.println("Inside");
// Put your calculator code here
System.out.println("Enter 1 to exit or 0 to continue");
cont = Integer.parseInt(br.readLine());
}
System.out.println("Outside");
}
}
The simplest way to do this, is to just call the main method when the calculation is complete and printed. You can achieve this by using main(null). Just add it right after your if-else block. Code below:
if(op==1){
Add(num1, num2);
}else if(op==2){
Sub(num1, num2);
}else if(op==3){
Mult(num1, num2);
}else if(op==4){
Div(num1, num2);
}
System.out.println(); // prints blank line
main(null);// calls main method (re-runs program)
This will complete the operation, then repeat the process.

Searching a string with multiple double values for one certain double value?

I have to create a calculator for my Computer Science class. I can calculate double values if they are only numbers like 3.4 or 6.8, while other double values like 64.7 or 6.78 will not work due to how I searched the String for the doubles. I am wondering if there is any way to find the doubles in the string or not. P.S. I know that testing the operator can be done a lot easier with switches. I am working on it.
public static void main(String[] args){
//Declares my input variables and Scanner variable
String firstInput;
String secondInput;
String userProblem;
char operator;
//Creates the scanner
Scanner userInput = new Scanner(System.in);
//Asks for input
System.out.println("Please enter a problem you would like to calculate (ex. \"2.0 * 4.3\")");
userProblem = userInput.nextLine();
//Finds the doubles in the string and the operator
firstInput = userProblem.substring(0, 3);
secondInput = userProblem.substring(6, 9);
operator = userProblem.charAt(4);
//parses the strings to doubles
double firstNumber = Double.parseDouble(firstInput);
double secondNumber = Double.parseDouble(secondInput);
//Tests for the operator and executes accordingly
if(operator == '+'){
System.out.println(firstNumber + secondNumber);
}
else{
if(operator == '-'){
System.out.println(firstNumber - secondNumber);
}
else{
if(operator == '*'){
System.out.println(firstNumber * secondNumber);
}
else{
if(operator == '/'){
System.out.println(firstNumber / secondNumber);
}
else{
if(operator == '%'){
System.out.println(firstNumber % secondNumber);
}
else{
System.out.println("You did not input correctly");
}
}
}
}
}
}
}
Use below code snippet for extracting two inputs and operator as well.
String[] tokensVal = userProblem.split("[-+*/%]");
firstInput = tokensVal[0].trim();
secondInput = tokensVal[1].trim();
operator = userProblem.charAt(tokensVal[0].length());

How to fix this code for a Java program that simulates a simple calculator?

Kindly help me to fix this code for a Java program that simulates a simple calculator.
It reads two integers and a character. If the character is a +, the sum is printed; if it is a -, the difference is printed; if it is a *, the product is printed; if it is a /, the quotient is printed; and if it is a %, the remainder is printed.
import java.util.Scanner;
class calc {
private int a,b,and;
private char c;
public static void main (String args[])
{
System.out.println ("Enter the first Integer");
Scanner scan = new Scanner (System.in);
a=scan.nextInt();
System.out.println("Enter the second Integer");
b=scan.nextInt();
System.out.println("Enter the operation sign");
c=scan.nextChar();
if (c=='+')
and=a+b;
else if (c=='-')
and=a-b;
else if (c=='*')
and=a*b;
else if (c=='/')
and=a/b;
else if (c=='%')
and=a%b;
else
{
System.out.println("Wrong operation");
exit(0);
}
System.out.println("The result is "+ ans);
}
}
Couple of things:
Make all your variables static so that you can use them within main or i would suggest move them within main.
Use nextLine().charAt(0) instead of nextChar which isn't defined in Scanner.
Instead of newxInt(); use nextInt(); api of Scanner
out is a static field (note lower case o), so change System.Out to System.out.
do an import static java.lang.System.exit; so you could use exit(0); without any issues from compiler.
Edit: Just for OP (Make sure you give meaningful name to variables) -
import static java.lang.System.exit;
import java.util.Scanner;
public class calc {
public static void main(String args[]) {
int a, b, ans = 0;
char c;
System.out.println("Enter the first Integer");
Scanner scan = new Scanner(System.in);
a = scan.nextInt();
scan.nextLine();
System.out.println("Enter the second Integer");
b = scan.nextInt();
scan.nextLine();
System.out.println("Enter the operation sign");
c = scan.nextLine().charAt(0);
if (c == '+')
ans = a + b;
else if (c == '-')
ans = a - b;
else if (c == '*')
ans = a * b;
else if (c == '/')
ans = a / b;
else if (c == '%')
ans = a % b;
else {
System.out.println("Wrong operation");
exit(0);
}
System.out.println("The result is " + ans);
}
}
Output:
Enter the first Integer
10
Enter the second Integer
20
Enter the operation sign
+
The result is 30
Change
c=scna.nextChar();
to
c=scan.nextChar();
Also change
exit(0)
to
System.exit(0)
b=scan.newxInt(); to b=scan.nextInt();
Change all Out to out

Why does my calculator automatically answer "0" before i can put my sign in?

Somewhere around line 15 it gives me issues.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //scanner object created
System.out.println("Enter your first number");
int nr1 = sc.nextInt();
System.out.println("Enter your second number");
int nr2 = sc.nextInt();
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
int ans = 0;
//somewhere around this line is where it is having the problems. it gives me the answer before i can put in my sign;
if(anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
}
else if(anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
}
else if(anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
}
else if(anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
}
System.out.println(ans);
System.out.println("To continue type yes");
String yes= sc.nextLine();
if(yes.equalsIgnoreCase("yes")) {
return;
}
}
}
it answers "0" whatever I enter before I can put in my sign
Enter your first number
9
Enter your second number
9
Enter your sign (+ , - , /, *)
0
To continue type yes
please tell me what I did wrong and possibly correct it so I can understand further
Try changing your sc.nextInt() lines to Integer.parseInt(sc.nextLine()). This should make your code work correctly.
EDIT: updated the code to include a while loop to make it so you can do multiple runs per your comment. This would also require you changing your last if statement to break; instead of return;
Scanner sc = new Scanner(System. in ); //scanner object created
while (true) {
System.out.println("Enter your first number");
int nr1 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your second number");
int nr2 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
int ans = 0;
//somewhere around this line is where it is having the problems. it gives me the answer before i can put in my sign;
if (anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
} else if (anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
} else if (anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
} else if (anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
}
System.out.println(ans);
System.out.println("To continue type yes");
String yes = sc.nextLine();
if (!yes.equalsIgnoreCase("yes")) {
break;
}
}
Change
String anvin = sc.nextLine();
to
String anvin = sc.next();
Also keep in mind that you might divide through zero ;-)
Edit:
also change
String yes= sc.nextLine();
to
String yes= sc.next();
Instead of sc.nextLine(); use sc.next();
I would suggest you this, you can not only learn using objects but learn a better way of writing managed codes too,
Calculator.java -> a class
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
//Instantiate
Scanner input = new Scanner(System.in);
Calculations calc = new Calculations();
// Variable declarations
double answer = 0, entry1 , entry2 ;
char operator;
// Start
System.out.println("***** Welcome to the Command line calculator program *****");
System.out.print("Please enter the first number :");
entry1 = input.nextDouble();
System.out.print("Please enter the second number:");
entry2 = input.nextDouble();
System.out.println("Please enter the operation : ");
System.out.println("***** Operations :- + -> Add ; - ->Substract ; / -> Divide ; * -> Multiply ; ^ : Power *****");
operator = input.next().charAt(0);
// Switch case
switch (operator){
case '+' : answer = calc.add(entry1, entry2);
break;
case '-' : answer = calc.substract(entry1, entry2);
break;
case '/' : answer = calc.divide(entry1, entry2);
break;
case '*' : answer = calc.multiply(entry1, entry2);
break;
case '^' : answer = calc.power(entry1, entry2);
break;
}
System.out.println(entry1 + " " + operator + " " + entry2 + " = " + answer);
}
}`
Calculations.java -->another class holding calculations
import java.math.*;
public class Calculations {
// Addition Method
double add (double first, double second){
double answer = first + second;
return answer;
}
// Substraction Method
double substract (double first, double second){
double answer = first - second;
return answer;
}
// Multiplication Method
double multiply (double first, double second){
double answer = first * second;
return answer;
}
// Division Method
double divide (double first, double second){
double answer = first / second;
return answer;
}
// Power Method
double power(double a, double b){
double answer =Math.pow(a, b);
return answer;
}
}

If Statement not working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am new to programming and would appreciate some help. The slightest bit of insight would be highly appreciated.
I have an issue with the following code. The program emulates a calculator but currently my main focus is on if and else if statements. The issue is that no matter what the user selects, the program will always add the two numbers i.e. 'number1' and 'number2' in the code
import java.util.*;
public class Input
{
private Scanner input;
public Input()
{
input = new Scanner(System.in);
}
public void calculation()
{
double number1, number2, answer;
String A, B, C, D, E;
String option;
A = "A"; B = "B"; C = "C"; D = "D"; E = "E"; //initialising the strings
System.out.println("add - option A \t (if your option is A, insert 'A')");
System.out.println("multiply - option B");
System.out.println("subtract - option C");
System.out.println("divide - option D");
System.out.println("power - option E (1st number - 'X' & 2nd number - 'n' following X^n)");
System.out.println("Remember Java is case sensitive, therefore, inserting 'a' as 'A' won't work");
System.out.println();
System.out.println("Insert your first number: ");
number1 = input.nextDouble();
System.out.println("Insert your second number: ");
number2 = input.nextDouble();
System.out.println("Choosing option: ");
option = input.next();
if(A == A)
{
answer = number1 + number2;
System.out.println("Your answer is: " + answer);
}
else if(B == B)
{
answer = number1 * number2;
System.out.println("Your answer is: " + answer);
}else if(C == C)
{
answer = number1 - number2;
System.out.println("Your answer is: " + answer);
}else if(D == D)
{
answer = number1 / number2;
System.out.println("Your answer is: " + answer);
}else if(E == E)
{
answer = Math.pow(number1, number2);
System.out.println("Your answer is: " + answer);
}else
{
System.out.println("Choose a suitable option");
}
}
}
Youre getting the selected option from user input in option = input.next(); line and than your not using it in your if statements.
Instead of if(A == A) use if(option.equals(A)) and so on for other cases.

Categories