Continuous user input calculator - java

so I'm trying to create a simple calculator program that have these features:
Continuously calculating user input depending on the operation
Exit the program when user inputs 'x' in any part of the program
So far, I'm able to just calculate 2 numbers but what I need is for it to keep going until the user presses or inputs 'x'.
Sample output I want would be like this:
Num 1: 5
Operator: +
Num 2: 5
---------------
Result: 10
Operator: +
Number 3: 10
--------
Result: 20
and this keeps going until X is pressed
Here's my code so far:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
int num1 = 0;
int num2 = 0;
int result = 0;
String operator;
boolean isNumber;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Enter First Number: ");
if (scanner.hasNextInt()) {
num1 = scanner.nextInt();
isNumber = true;
} else {
System.err.println("Not a valid number");
isNumber = false;
scanner.next();
}
} while (!(isNumber));
System.out.println("Enter Operator ");
operator = scanner.next();
while (!operator.equals("+") && !operator.equals("-") && !operator.equals("*") && !operator.equals("/")) {
System.err.println("Invalid operator. Enter Correct Operation:");
operator = scanner.next();
}
do {
System.out.println("Enter Second Number: ");
if (scanner.hasNextInt()) {
num2 = scanner.nextInt();
isNumber = true;
} else {
System.err.println("Invalid Input. Enter Correct Number");
isNumber = false;
scanner.next();
}
} while (!(isNumber));
switch (operator) {
case "+":
addition(num1, num2, result);
break;
case "-":
subtraction(num1, num2, result);
break;
case "*":
multiplication(num1, num2, result);
break;
case "/":
division(num1, num2, result);
case "x":
System.exit(0);
}
}
public static void addition(int num1, int num2, int result) {
result = num1 + num2;
System.out.println("---------------------------");
System.out.println("RESULT:" + result);
}
public static void subtraction(int num1, int num2, int result) {
result = num1 - num2;
System.out.println("---------------------------");
System.out.println("RESULT:" + result);
}
public static void multiplication(int num1, int num2, int result) {
result = num1 * num2;
System.out.println("---------------------------");
System.out.println("RESULT:" + result);
}
public static void division(int num1, int num2, int result) {
result = num1 / num2;
System.out.println("---------------------------");
System.out.println("RESULT:" + result);
}
}

Related

Creating a calculator that calls the methods from a separate class using scanner

I'm creating a calculator where each of the calculator's functions have to be in a separate class and called from the main method using scanner input.
1.Add
2.Subtract
3.Multiplication
4.Division
5.Square
6.Power
7.Mod operation
8.Factorial
0.Quit
I must create each method called by an object. The calculator requires one main class (has main () method) and one user defined class which has above calculating methods. The program must let the user choose an operation (one of above calculations) and operand(s) (numbers). Some calculations require two operands. (e.g. A + B, AB) Some calculations require one operand. (e.g. A2, N!) Additional functions:
•Let the calculation function continues until user wants to exit this program.
•When one calculation is done, let user choose another operation.
•This program terminates when user selects END option.
•Implement all operations. Do not use Java library math methods.
I have the code for a program that is using switch statement and case, but our class hasn't even learned any of that. I have looked everywhere online for the past two days and just can't figure it out, so apologies if the solution is simple, and thank you to all help in advance. Here is the code to my program so far.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int choice;
do
{
System.out.println("[1] Add ");
System.out.println("[2] Subtract ");
System.out.println("[3] Multiply ");
System.out.println("[4] Division ");
System.out.println("[5] Square ");
System.out.println("[6] Power ");
System.out.println("[7] Mod Operation ");
System.out.println("[8] Factorial ");
System.out.println("[0] Quit ");
System.out.println("Please enter your choice: ");
choice = s.nextInt();
int num1, num2;
switch(choice)
{
case 1 : System.out.println("Enter two numbers to add: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The sum of " + num1 + " and " + num2 +
" is: " + add(num1, num2));
break;
case 2 : System.out.println("Enter two numbers to subtract: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The difference of " + num1 + " and " + num2 +
" is: " + diff(num1, num2));
break;
case 3 : System.out.println("Enter two numbers to multiply: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The product of " + num1 + " and " + num2 +
" is: " + prod(num1, num2));
break;
case 4 : System.out.println("Enter two numbers to divide: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The quotient of " + num1 + " and " + num2 +
" is: " + quo(num1, num2));
break;
case 5 : System.out.println("A number to square: ");
num1 = s.nextInt();
System.out.println("The square of " + num1 + " is: " + square(num1));
break;
case 6 : System.out.println("Enter the base and the exponent: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The power of " + num1 + " to the " + num2 +
"th power is: " + power(num1, num2));
break;
case 7 : System.out.println("Enter two numbers to get the interger remainder of (modulo): ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The modulo of " + num1 + " and " + num2 +
" is: " + mod(num1, num2));
break;
case 8 : System.out.println("Enter a number to get the factorial of: ");
num1 = s.nextInt();
System.out.println("The factorial of " + num1 + " is: " + factorial(num1));
break;
case 0: System.out.println("Thank you for using my program...good bye!");
System.exit(0);
}
}
while(choice != 0);
s.close();
}
public static int add(int num1, int num2)
{
return num1 + num2;
}
public static int diff(int num1, int num2)
{
return num1 - num2;
}
public static int prod(int num1, int num2)
{
return num1 * num2;
}
public static double quo(int num1, int num2)
{
return (double)num1 / num2;
}
public static int mod(int num1, int num2)
{
return num1 % num2;
}
public static long power(int base, int exp)
{
long result = 1;
while (exp != 0)
{
result *= base;
--exp;
}
return result;
}
public static int square(int num)
{
return num * num;
}
public static int factorial(int base)
{
if (base == 0)
return 1;
else
return(base * factorial(base - 1));
}
}
you can use a separate class called Functions with static methods
public class Functions{
public static int add(int num1, int num2)
{
return num1 + num2;
}
public static int diff(int num1, int num2)
{
return num1 - num2;
}
public static int prod(int num1, int num2)
{
return num1 * num2;
}
public static double quo(int num1, int num2)
{
return (double)num1 / num2;
}
public static int mod(int num1, int num2)
{
return num1 % num2;
}
public static long power(int base, int exp)
{
long result = 1;
while (exp != 0)
{
result *= base;
--exp;
}
return result;
}
public static int square(int num)
{
return num * num;
}
public static int factorial(int base)
{
if (base == 0)
return 1;
else
return(base * factorial(base - 1));
}
}
and you call these methods Functions.add(num1, num2))
I'm not sure if that what you want
Here is an approach, which may be useful to you. I have done implementation for Addition and Subtraction, you can follow the same thing for other operations as well. You may want to have abstract class for single operand operations as well.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int choice;
do {
System.out.println("[1] Add ");
System.out.println("[2] Subtract ");
System.out.println("[3] Multiply ");
System.out.println("[4] Division ");
System.out.println("[5] Square ");
System.out.println("[6] Power ");
System.out.println("[7] Mod Operation ");
System.out.println("[8] Factorial ");
System.out.println("[0] Quit ");
System.out.println("Please enter your choice: ");
choice = s.nextInt();
int num1, num2;
switch (choice) {
case 1:
Addition addition = new Addition(s);
addition.performOperation();
break;
case 2:
Subtraction subtraction = new Subtraction(s);
subtraction.performOperation();
break;
case 3:
System.out.println("Enter two numbers to multiply: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The product of " + num1 + " and " + num2 +
" is: " + prod(num1, num2));
break;
case 4:
System.out.println("Enter two numbers to divide: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The quotient of " + num1 + " and " + num2 +
" is: " + quo(num1, num2));
break;
case 5:
System.out.println("A number to square: ");
num1 = s.nextInt();
System.out.println("The square of " + num1 + " is: " + square(num1));
break;
case 6:
System.out.println("Enter the base and the exponent: ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The power of " + num1 + " to the " + num2 +
"th power is: " + power(num1, num2));
break;
case 7:
System.out.println("Enter two numbers to get the interger remainder of (modulo): ");
num1 = s.nextInt();
num2 = s.nextInt();
System.out.println("The modulo of " + num1 + " and " + num2 +
" is: " + mod(num1, num2));
break;
case 8:
System.out.println("Enter a number to get the factorial of: ");
num1 = s.nextInt();
System.out.println("The factorial of " + num1 + " is: " + factorial(num1));
break;
default:
System.out.println("Your choices should be 0 to 8!");
break;
}
}
while (choice != 0);
s.close();
System.out.println("Thank you for using my program...good bye!");
System.exit(0);
}
public static int prod(int num1, int num2) {
return num1 * num2;
}
public static double quo(int num1, int num2) {
return (double) num1 / num2;
}
public static int mod(int num1, int num2) {
return num1 % num2;
}
public static long power(int base, int exp) {
long result = 1;
while (exp != 0) {
result *= base;
--exp;
}
return result;
}
public static int square(int num) {
return num * num;
}
public static int factorial(int base) {
if (base == 0)
return 1;
else
return (base * factorial(base - 1));
}
}
abstract class OperationWithTwoOperands {
protected String prompt;
private Scanner scanner;
public OperationWithTwoOperands(Scanner scanner) {
this.scanner = scanner;
}
public void performOperation() {
System.out.println(prompt);
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
operation(num1, num2);
}
abstract protected void operation(int operand1, int operand2);
}
class Addition extends OperationWithTwoOperands {
public Addition(Scanner scanner) {
super(scanner);
prompt = "Enter two numbers to add:";
}
#Override
protected void operation(int num1, int num2) {
System.out.println("The sum of " + num1 + " and " + num2 + " is: " + (num1 + num2));
}
}
class Subtraction extends OperationWithTwoOperands {
public Subtraction(Scanner scanner) {
super(scanner);
prompt = "Enter two numbers to subtract:";
}
#Override
protected void operation(int num1, int num2) {
System.out.println("The difference of " + num1 + " and " + num2 + " is: " + (num1 - num2));
}
}

How to print error message when user enters anything that is not a double?

I am trying to create a Java program that reads a double value from the user, Printing the difference between these two numbers so that the difference is always positive. I need to display an Error message if anything other than a number is entered. Please help, thank you !!
When I run the program and enter the second double value nothing happens. I have also tried adding try and catch but I get errors saying num1 cannot be resolved to a variable :(
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
//Reads input
Scanner sc = new Scanner(System.in);
System.out.println ("Please enter a double vaule: ");
double num1 = Math.abs(sc.nextDouble());
System.out.println("Please enter a second double vaule: " );
double num2 = Math.abs(sc.nextDouble());
double total = 0;
double total2 = 0;
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1>num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
}
if ((num1 < num2)); {
total2 = ((num2 - num1));
System.out.println("The difference is "+ total2);
}
}else {
System.out.println("Wrong vaule entered");
}
}
}
You have the right idea. You just need to remove the semicolon (;) after the last if and properly nest your conditions:
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1 > num2) {
total = (num1 - num2);
System.out.println("The difference is " + total);
}
else if (num1 < num2) {
total2 = (num2 - num1);
System.out.println("The difference is "+ total2);
}
} else {
System.out.println("Wrong vaule entered");
}
Try running your code and when you enter your first double, type in something random like "abc". What happens? In your console it should display an error named java.util.InputMismatchException. You can use a try catch block like so:
try {
//tries to get num1 and num2
double num1 = Math.abs(sc.nextDouble());
double num2 = Math.abs(sc.nextDouble());
} catch (java.util.InputMismatchException i){
//will only go here if either num1 or num2 isn't a double
System.out.println("error");
}
Basically, the code will try to get num1 and num2. However if you enter a non-double, it'll "catch" the java.util.InputMismatchException and go to the catchblock
I might've misinterpreted your question, but if you want to find the absolute value of the difference between num1 and num2, all you have to do is:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Please enter a double value: ");
double num1 = sc.nextDouble();
System.out.println("Please enter a double value: ");
double num2 = sc.nextDouble();
System.out.println("The difference is: " + Math.abs(num1 - num2));
} catch (java.util.InputMismatchException i) {
System.out.println("error");
}
}
}
To show error message until the user enters a double value I used a while loop for each value (num1 and num2).
If user enters a wrong value "Wrong vaule entered, Please enter again: " message will show and waits for the next input sc.next();
If user enters a double value check will be false and exits while loop
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
// Reads input
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a double vaule: ");
double num1 = 0;
double num2 = 0;
double total = 0;
double total2 = 0;
boolean check = true;
while (check) {
if (sc.hasNextDouble()) {
num1 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
check = true; // that's for second control
System.out.println("Please enter a second double vaule: ");
while (check) {
if (sc.hasNextDouble()) {
num2 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
if (num1 > num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
} else if ((num1 < num2)) {
total2 = ((num2 - num1));
System.out.println("The difference is " + total2);
}
}
}

Checking to see if a numbe is prime using methods

The answer is probably staring me in the face but I have been looking at this so long the words are blurring together. The assignment is to have the user input 3 numbers, add the numbers together using a method, then to determine if the sum is a prime number using a different method.
package chpt6_Project;
import java.util.Scanner;
public class Chpt6_Project {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1;
int num2;
int num3;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first number: ");
num1 = scan.nextInt();
System.out.println("Enter the second number: ");
num2 = scan.nextInt();
System.out.println("Enter the third number: ");
num3 = scan.nextInt();
Chpt6_Project.sum(num1, num2, num3);
if(isPrime()) {
System.out.println("The number is prime");
} else {
System.out.println("The number is not prime.");
}
}
public static void sum(int num1, int num2, int num3) {
int total = num1 + num2 + num3;
System.out.println(total);
}
public static boolean isPrime(int total) {
if((total > 2 && total % 2 == 0) || total == 1) {
return false;
}
for (int i = 3; i <= (int)Math.sqrt(total); i += 2) {
if (total % i == 0) {
return false;
}
}
return true;
}
}
Edit the code as follow and you should do the trick.
The sum function now returns the sum calculated, this value is passed by main to the isPrime function which will return the right value
package chpt6_Project;
import java.util.Scanner;
public class Chpt6_Project {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1;
int num2;
int num3;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first number: ");
num1 = scan.nextInt();
System.out.println("Enter the second number: ");
num2 = scan.nextInt();
System.out.println("Enter the third number: ");
num3 = scan.nextInt();
if(isPrime(Chpt6_Project.sum(num1, num2, num3))) {
System.out.println("The number is prime");
} else {
System.out.println("The number is not prime.");
}
}
public static int sum(int num1, int num2, int num3) {
int total = num1 + num2 + num3;
System.out.println(total);
return total;
}
public static boolean isPrime(int total) {
if((total > 2 && total % 2 == 0) || total == 1) {
return false;
}
for (int i = 3; i <= (int)Math.sqrt(total); i += 2) {
if (total % i == 0) {
return false;
}
}
return true;
}
Morover i guess this is an homework but there are better way of doing this. For example, there is no need for a sum function.

basic calculator methods to ask for new numbers

So I'm creating a basic calculator for class using java that will ask the user for 2 numbers then will ask them what sort of calculation they want. It works but not as I wanted and i'm out of patience trying to figure out these methods. Just started learning them by the way.
Ok so, what i need held with is i would like to tell the user that its bad math to divide by 0 and that he will need to change his numbers. But how do I get the prompt to come back up if he inputs a 0 as one of the numbers?
for example, here is a snippet of my code for division:
public static float divide(float num1, float num2){
if ((num1 == 0) || (num2 == 0)){
JOptionPane.showMessageDialog(null, "numbers cannot be divisible by 0");
//I would like to give the user an option here to change his numbers to something else.
return 0;}
else
return num1 / num2;
please help.
package assignment4_main;
import javax.swing.JOptionPane;
public class Assignment4_Main {
public static void main(String[] args) {
float result;
float num1 = Float.parseFloat(JOptionPane.showInputDialog(null, "Enter first number: ", "Calculator" , JOptionPane.QUESTION_MESSAGE));
float num2 = Float.parseFloat(JOptionPane.showInputDialog(null, "Enter second number: ", "Calculator", JOptionPane.QUESTION_MESSAGE));
int userInput = Integer.parseInt(JOptionPane.showInputDialog(null, "What would you like to do with these numbers?\n" + "1- Add 2- Subtract 3- Multiply 4- Divide 5- Quit", "Calculator", JOptionPane.QUESTION_MESSAGE));
switch(userInput){
case 1:
{result = add(num1, num2);
JOptionPane.showMessageDialog(null, "Addition = " + result);
break;}
case 2:
{result = subtract(num1, num2);
JOptionPane.showMessageDialog(null, "Subtraction = " + result);
break;}
case 3:
{result = multiply(num1, num2);
JOptionPane.showMessageDialog(null, "Multiplication = " + result);
break;}
case 4:
{result = divide(num1, num2);
JOptionPane.showMessageDialog(null, "Division = " + result);
break;}
case 5:
break;
}
}
public static float add(float num1, float num2){
return num1 + num2;
}
public static float subtract(float num1, float num2){
return num1 - num2;
}
public static float multiply(float num1, float num2){
return num1 * num2;
}
public static float divide(float num1, float num2){
if ((num1 == 0) || (num2 == 0)){
JOptionPane.showMessageDialog(null, "numbers cannot be divisible by 0");
return 0;}
else
return num1 / num2;
}
}
There are more elegant solutions to this of course, but this one should get you on the way:
public static void main(String[] args) {
int number;
while (true) {
Object[] message = {"Input some number that is not 0: "};
String numberString = JOptionPane.showInputDialog(null, message, "Add New", JOptionPane.OK_CANCEL_OPTION);
try {
number = Integer.parseInt(numberString);
} catch (NumberFormatException e) {
continue;
}
if (number != 0) {
break;
}
}
System.out.println(number);
}

Basic calculator in Java

I'm trying to create a basic calculator in Java. I'm quite new to programming so I'm trying to get used to it.
import java.util.Scanner;
import javax.swing.JOptionPane;
public class javaCalculator
{
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("please enter the first number");
num1 = input.nextInt();
System.out.println("please enter the second number");
num2 = input.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation");
operation = op.next();
if (operation == "+");
{
System.out.println("your answer is" + (num1 + num2));
}
if (operation == "-");
{
System.out.println("your answer is" + (num1 - num2));
}
if (operation == "/");
{
System.out.println("your answer is" + (num1 / num2));
}
if (operation == "*")
{
System.out.println("your answer is" + (num1 * num2));
}
}
}
This is my code. It prompts for the numbers and operation, but displays the answers all together ?
Remove the semi-colons from your if statements, otherwise the code that follows will be free standing and will always execute:
if (operation == "+");
^
Also use .equals for Strings, == compares Object references:
if (operation.equals("+")) {
Here is simple code for calculator so you can consider this
import java.util.*;
import java.util.Scanner;
public class Hello {
public static void main(String[] args)
{
System.out.println("Enter first and second number:");
Scanner inp= new Scanner(System.in);
int num1,num2;
num1 = inp.nextInt();
num2 = inp.nextInt();
int ans;
System.out.println("Enter your selection: 1 for Addition, 2 for substraction 3 for Multiplication and 4 for division:");
int choose;
choose = inp.nextInt();
switch (choose){
case 1:
System.out.println(add( num1,num2));
break;
case 2:
System.out.println(sub( num1,num2));
break;
case 3:
System.out.println(mult( num1,num2));
break;
case 4:
System.out.println(div( num1,num2));
break;
default:
System.out.println("Illigal Operation");
}
}
public static int add(int x, int y)
{
int result = x + y;
return result;
}
public static int sub(int x, int y)
{
int result = x-y;
return result;
}
public static int mult(int x, int y)
{
int result = x*y;
return result;
}
public static int div(int x, int y)
{
int result = x/y;
return result;
}
}
CompareStrings with equals(..) not with ==
if (operation.equals("+")
{
System.out.println("your answer is" + (num1 + num2));
}
if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
if (operation .equals( "*"))
{
System.out.println("your answer is" + (num1 * num2));
}
And the ; after the conditions was an empty statement so the conditon had no effect at all.
If you use java 7 you can also replace the if statements with a switch.
In java <7 you can test, if operation has length 1 and than make a switch for the char [switch (operation.charAt(0))]
import java.util.Scanner;
public class AdditionGame {
public static void main(String[] args) {
// TODO Auto-generated method stub
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("Please Enter The First Number");
num1 = input.nextInt();
System.out.println("Please Enter The Second Number");
num2 = input.nextInt();
Scanner op = new Scanner (System.in);
System.out.println("Please Enter The Operation");
operation = op.next();
if (operation.equals("+"))
{
System.out.println("Your Answer is "+(num1 + num2));
}
else if (operation.equals("-"))
{
System.out.println("Your Answer is "+(num1 - num2));
}
else if (operation.equals("*"))
{
System.out.println("Your Answer is "+(num1 * num2));
}
else if (operation.equals("/"))
{
System.out.println("Your Answer is "+(num1 / num2));
}
}
}
Java program example for making a simple Calculator:
import java.util.Scanner;
public class Calculator
{
public static void main(String args[])
{
float a, b, res;
char select, ch;
Scanner scan = new Scanner(System.in);
do
{
System.out.print("(1) Addition\n");
System.out.print("(2) Subtraction\n");
System.out.print("(3) Multiplication\n");
System.out.print("(4) Division\n");
System.out.print("(5) Exit\n\n");
System.out.print("Enter Your Choice : ");
choice = scan.next().charAt(0);
switch(select)
{
case '1' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a + b;
System.out.print("Result = " + res);
break;
case '2' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a - b;
System.out.print("Result = " + res);
break;
case '3' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a * b;
System.out.print("Result = " + res);
break;
case '4' : System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a / b;
System.out.print("Result = " + res);
break;
case '5' : System.exit(0);
break;
default : System.out.print("Wrong Choice!!!");
}
}while(choice != 5);
}
}
maybe its better using the case instead of if dunno if this eliminates the error, but its cleaner i think.. switch (operation){case +: System.out.println("your answer is" + (num1 + num2));break;case -: System.out.println("your answer is" - (num1 - num2));break; ...
import java.util.Scanner;
import javax.swing.JOptionPane;
public class javaCalculator
{
public static void main(String[] args)
{
int num1;
int num2;
String operation;
Scanner input = new Scanner(System.in);
System.out.println("please enter the first number");
num1 = input.nextInt();
System.out.println("please enter the second number");
num2 = input.nextInt();
Scanner op = new Scanner(System.in);
System.out.println("Please enter operation");
operation = op.next();
if (operation.equals("+"))
{
System.out.println("your answer is" + (num1 + num2));
}
else if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
else if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
else if (operation.equals("*"))
{
System.out.println("your answer is" + (num1 * num2));
}
else
{
System.out.println("Wrong selection");
}
}
}
public class SwitchExample {
public static void main(String[] args) throws Exception {
System.out.println(":::::::::::::::::::::Start:::::::::::::::::::");
System.out.println("\n\n");
System.out.println("1. Addition");
System.out.println("2. Multiplication");
System.out.println("3. Substraction");
System.out.println("4. Division");
System.out.println("0. Exit");
System.out.println("\n");
System.out.println("Enter Your Choice ::::::: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int usrChoice = Integer.parseInt(str);
switch (usrChoice) {
case 1:
doAddition();
break;
case 2:
doMultiplication();
break;
case 3:
doSubstraction();
break;
case 4:
doDivision();
break;
case 0:
System.out.println("Thank you.....");
break;
default:
System.out.println("Invalid Value");
}
System.out.println(":::::::::::::::::::::End:::::::::::::::::::");
}
public static void doAddition() throws Exception {
System.out.println("******* Enter in Addition Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Addition : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Addition : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 + no2;
System.out.println("Addition of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doSubstraction() throws Exception {
System.out.println("******* Enter in Substraction Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Substraction : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Substraction : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 - no2;
System.out.println("Substraction of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doMultiplication() throws Exception {
System.out.println("******* Enter in Multiplication Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Multiplication : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Multiplication : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
int result = no1 * no2;
System.out.println("Multiplication of " + no1 + " and " + no2 + " is ::::::: " + result);
}
public static void doDivision() throws Exception {
System.out.println("******* Enter in Dividion Process ********");
String strNo1, strNo2;
System.out.println("Enter Number 1 For Dividion : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
strNo1 = br.readLine();
System.out.println("Enter Number 2 For Dividion : ");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
strNo2 = br1.readLine();
int no1 = Integer.parseInt(strNo1);
int no2 = Integer.parseInt(strNo2);
float result = no1 / no2;
System.out.println("Division of " + no1 + " and " + no2 + " is ::::::: " + result);
}
}
we can simply use in.next().charAt(0); to assign + - * / operations as characters by initializing operation as a char.
import java.util.*;
public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char operation;
int num1;
int num2;
System.out.println("Enter First Number");
num1 = in.nextInt();
System.out.println("Enter Operation");
operation = in.next().charAt(0);
System.out.println("Enter Second Number");
num2 = in.nextInt();
if (operation == '+')//make sure single quotes
{
System.out.println("your answer is " + (num1 + num2));
}
if (operation == '-')
{
System.out.println("your answer is " + (num1 - num2));
}
if (operation == '/')
{
System.out.println("your answer is " + (num1 / num2));
}
if (operation == '*')
{
System.out.println("your answer is " + (num1 * num2));
}
}
}
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
int x,
int y;
Scanner input=new Scanner(System.in);
System.out.println("Enter Number 1");
x=input.nextInt();
System.out.println("Enter Number 2");
y=input.nextInt();
System.out.println("Please enter operation + - / or *");
Scanner op=new Scanner(System.in);
String operation = op.next();
if (operation.equals("+")){
System.out.println("Your Answer: " + (x+y));
}
if (operation.equals("-")){
System.out.println("Your Answer: "+ (x-y));
}
if (operation.equals("/")){
System.out.println("Your Answer: "+ (x/y));
}
if (operation.equals("*")){
System.out.println("Your Answer: "+ (x*y));
}
}
}

Categories

Resources