basic calculator methods to ask for new numbers - java

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);
}

Related

Continuous user input calculator

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);
}
}

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 do I stop my code from executing every println after I execute the right code?

Scanner scan = new Scanner(System.in);
System.out.print("Enter 2 numbers: ");
int num1 = scan.nextInt();
int num2 = scan.nextInt();
System.out.println("Numbers Saved! Choose your operator + - * / ");
String operator = scan.next();
int result;
result = (operator.equals("+")) ? (num1 + num2) : (num1);
System.out.println("The addition result is " +result);
result = (operator.equals("-")) ? (num1 - num2) : (num1);
System.out.println("The subtraction result is " +result);
result = (operator.equals("*")) ? (num1 * num2) : (num1);
System.out.println("The multiplication result is " +result);
result = (operator.equals("/")) ? (num1 / num2) : (num1);
System.out.println("The division result is " +result);
}
}
This is my simple calculator code, for example when i choose the + option, it runs all System.out.println lines, how do I prevent it from doing this and only execute the println that matches the operator?
Try a switch:
switch (operator) {
case "+":
result = num1 + num2;
System.out.println("The addition result is " + result);
break;
case "-":
result = num1 - num2;
System.out.println("The subtraction result is " + result);
break;
case "-":
result = num1 * num2;
System.out.println("The multiplication result is " + result);
break;
case "/":
result = num1 / num2;
System.out.println("The integer division result is " + result);
break;
default:
throw IllegalArgumentException("Unsupported operator: " + operator);
}
I would encapsulate the operator logic (resolution and evaluation) into an enum. Like,
enum Oper {
ADDITION("+"), SUBTRACTION("-"), MULTIPLICATION("*"), DIVISION("/");
Oper(String symbol) {
this.symbol = symbol;
}
public int eval(int a, int b) {
switch (this) {
case ADDITION: return a + b;
case SUBTRACTION: return a - b;
case MULTIPLICATION: return a * b;
case DIVISION: return a / b;
}
return -1;
}
private String symbol;
public static Oper from(String operator) {
for (Oper o : values()) {
if (o.symbol.equals(operator)) {
return o;
}
}
return null;
}
}
That simplifies the logic in main, just resolve the operator and evaluate it. Like,
Oper o = Oper.from(operator);
System.out.printf("The %s result is %d%n", o.name().toLowerCase(), o.eval(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);
}
}
}

Java calculate numbers in a string

I'm making a calculator program that can read in a string like this:
67+12-45
How can I perform the function that the string is intending to do? Here's what I've tried so far:
public static int calculate(String expression, int num1, int num2)
{
int answer = 0;
switch(expression)
{
case "+":
if(answer != 0)
{
answer = answer + num1 + num2;
}
else
{
answer = num1 + num2;
}
break;
case "-":
if(answer != 0)
{
answer = answer + (num1 - num2);
}
else
{
answer = num1 - num2;
}
break;
case "*":
if(answer != 0)
{
answer = answer + (num1 * num2);
}
else
{
answer = num1 * num2;
}
break;
case "/":
if(answer != 0)
{
answer = answer + (num1 / num2);
}
else
{
answer = num1 / num2;
}
break;
case "%":
if(answer != 0)
{
answer = answer + (num1 % num2);
}
else
{
answer = num1 % num2;
}
break;
}
return answer;
}
Is there a simpler way to perform the function intended in the string?
the easiest way to achieve this is using eval, you can do this:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval("67+12-45"); //you can insert any expression here
This talk describes an Object Oriented solution to this problem:
http://youtu.be/4F72VULWFvc?t=7m40s
Essentially, you can parse the string into an expression tree that can be evaluated.

Categories

Resources