Java calculate numbers in a string - java

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.

Related

After I've inputed the number of questions and the difficulty it stops running

After I've inputted the number of questions and the question difficulty the code stops running like it's finished. It doesn't display any errors it just stops. This is a code I'm writing for an introductory Java programming class and its meant to keep displaying operations for the user to solve, then say whether they were right or wrong and give them a grade.
import java.util.Scanner;
import java.util.Random;
public class MathPractice {
public static int getNumberOfQuestions(int questions) {
while (questions >= 1 || questions < 1) {
if (questions >= 1) {
questions = questions;
} else {
Scanner keyboard = new Scanner(System.in);
System.out.print("The number of questions must be 1 or more. ");
System.out.print("How many questions do you want? ");
questions = keyboard.nextInt();
}}
return questions;
}
public static int getQuestionDifficulty(int difficulty) {
while (difficulty <= 1 || difficulty >= 2) {
if (difficulty < 1 || difficulty > 2) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Valid levels are 1 or 2. Please re-enter. ");
System.out.print("What difficulty level do you want (1=low or 2=high)? ");
difficulty = keyboard.nextInt();
} else {
difficulty = difficulty;
}}
return difficulty;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
char keepGoing = 'y';
char stop = 'n';
char answer = keepGoing;
for(int counter = 0; counter >= 0; counter++) {
if (answer == stop) {
System.out.print("Session Statistics");
} else if (answer == keepGoing) {
System.out.print("How many questions do you want? ");
int questions = keyboard.nextInt();
System.out.print("What difficulty level do you want (1=low or 2=high)? ");
int difficulty = keyboard.nextInt();
questions = getNumberOfQuestions(questions);
difficulty = getQuestionDifficulty(difficulty);
for (int i = 0; i < questions; i++) {
if (difficulty == 1) {
Random random = new Random();
String operatorSwitch = null;
int num1 = 0;
int num2 = random.nextInt(10);
int num3 = random.nextInt(10);
int num4 = random.nextInt(9) +1;
int operator = random.nextInt(4);
switch (operator){
case 0: operatorSwitch = "+";
num1 = (num2 + num3);
break;
case 1: operatorSwitch = "-";
num1 = (num2 - num3);
break;
case 2: operatorSwitch = "*";
num1 = (num2 * num3);
break;
case 3: operatorSwitch = "/";
num3 = num4;
num1 = (num2 / num3);
break;
}
System.out.print("Question #" + i + ": What is " + num2 + operatorSwitch + num3 + "? ");
int input = keyboard.nextInt();
if(input != num1) {
System.out.print("Wrong... The answer is " + num1);
counter = counter - 1;
} else if(input == num1) {
System.out.print("Correct!");
}
System.out.printf("You answered " + counter + "out of " + questions + "correctly (%.2f%%)", (counter / questions));
System.out.print("Would you like another set of questions? (y/n) ");
answer = keyboard.next().charAt(0);
} else if (difficulty == 2) {
Random random = new Random();
String operatorSwitch = null;
int num1 = 0;
int num2 = random.nextInt(19) - 9;
int num3 = random.nextInt(19) - 9;
int num4 = random.nextInt(9) + 1;
int operator = random.nextInt(5);
switch (operator){
case 0: operatorSwitch = "+";
num1 = (num2 + num3);
break;
case 1: operatorSwitch = "-";
num1 = (num2 - num3);
break;
case 2: operatorSwitch = "*";
num1 = (num2 * num3);
break;
case 3: operatorSwitch = "/";
num3 = num4;
num1 = (num2 / num3);
break;
case 4: operatorSwitch = "%";
num1 = (num2 % num3);
}
System.out.print("Question #" + i + ": What is " + num2 + operatorSwitch + num3 + "? ");
int input = keyboard.nextInt();
if(input != num1) {
System.out.println("Wrong... The answer is " + num1);
counter = counter - 1;
} else if(input == num1) {
System.out.println("Correct!");
}
System.out.printf("You answered " + counter + "out of " + questions + "correctly (%.2f%%)", (counter / questions));
System.out.print("Would you like another set of questions? (y/n) ");
answer = keyboard.next().charAt(0);
}}
}
}
}
}
while (questions >= 1 || questions < 1) {
if (questions >= 1) {
questions = questions;
else [...]
This part will probably loop infinitely, once you enter any number >0.
Actually, this is also (and especially) true for your loop in getQuestionDifficulty()

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

Simple calculator program in Java

I am a newbie coder in Java and I am trying to make this calculator in java where a user can enter two numbers and select the operation to be done on those numbers. However when the code comes to selecting the operator it skips the user input and the if statement and directly implements the else statement.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner Calc = new Scanner(System.in);
int n1;
int n2;
int Answer;
System.out.println("Enter the first number: ");
n1 = Calc.nextInt();
System.out.println("Enter the second number:" );
n2 = Calc.nextInt();
System.out.println("Select the order of operation: ");
char operator = Calc.nextLine().charAt(0);
if (operator == '+') {
Answer = (n1 + n2);
System.out.println("Answer:" + Answer);
}
if (operator == '-') {
Answer = (n1 - n2);
System.out.println("Answer:" + Answer);
}
if (operator == '*') {
Answer = (n1 * n2);
System.out.println("Answer:" + Answer);
}
if (operator == '/') {
Answer = (n1/n2);
System.out.println("Answer:" + Answer);
}
else {
System.out.println("not implemented yet. Sorry!");
}
}
}
Add Calc.nextLine(); after n2 = Calc.nextInt(); to consume the line feed.
You are also not using else if so all those if conditions will be checked even if previous if already matched (resulting in your final else being executed as long as operator not '/').
In this case you should probably just use a switch block.
I made some changes to the code, this should work with you, but I also recommend using a switch.
Scanner Input = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int num1 = Input.nextInt();
System.out.print("Enter an operator: ");
char operator = Input.next().charAt(0);
System.out.print("Enter a second number: ");
int num2 = Input.nextInt();
// this part of decision, it doesn't work.
if ('+' == operator) {
System.out.println("Your result is " + (num1 + num2));
} else if ('-' == operator) {
System.out.println("Your result is " + (num1 - num2));
} else if ('*' == operator) {
System.out.println("Your result is " + (num1 * num2));
} else if ('/' == operator) {
System.out.println("Your result is " + (num1 / num2));
}else {
System.out.println("Your answer is not valid");
}
} catch (InputMismatchException e) {
System.out.println("similar to try and except in Python");
}

Reopening a java program that is running

I have a calculator that I've been working on for school.
It's not going to have a typical calculator GUI though.
I have a beta version where I use input boxes in order to take the input.
I was actually wondering if there was a way to make a function to close it and then reopen it sort of like a loop.
import javax.swing.JOptionPane;
public class JOptionPaneCalc {
public static void main(String [] args){
char o = ' ';
String input = " ";
double num1 = 0;
double num2 = 0;
double result = 0;
while (true){
input = JOptionPane.showInputDialog("What is your operand? ");
o = input.charAt(0);
if (o == '/') {
result = num1 / num2;
break;
} else if (o == '*') {
result = num1 * num2;
break;
} else if (o == '+') {
result = num1 + num2;
break;
} else if (o == '-') {
result = num1 - num2;
break;
}else if (o == 'q'){
System.exit(0);
}
}
input = JOptionPane.showInputDialog("What is your first number? ");
num1 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("What is your second number? ");
num2 = Double.parseDouble(input);
if (o == '/') {
result = num1 / num2;
} else if (o == '*') {
result = num1 * num2;
} else if (o == '+') {
result = num1 + num2;
} else if (o == '-') {
result = num1 - num2;
}else if (o == 'q'){
System.exit(0);
}
JOptionPane.showMessageDialog(null ,"Your answer is : " + result);
}
}
This is what I have, hopefully you can help me
There are quite a few issues with your code. If o == 'q', then your program will exit for good.
}else if (o == 'q'){
System.exit(0);
}
Read about repetition.
If you want your program to loop, then you should write it at least like this:
public static void main(String[] args) {
char o;
String input;
double num1;
double num2;
double result=0.;
input = JOptionPane.showInputDialog("What is your operand? ");
o = input.charAt(0);
while (o!='q') {
input = JOptionPane.showInputDialog("What is your first number? ");
num1 = Double.parseDouble(input);
input = JOptionPane.showInputDialog("What is your second number? ");
num2 = Double.parseDouble(input);
if (o == '/') {
result = num1 / num2;
} else if (o == '*') {
result = num1 * num2;
} else if (o == '+') {
result = num1 + num2;
} else if (o == '-') {
result = num1 - num2;
}
JOptionPane.showMessageDialog(null ,"Your answer is : " + result);
input = JOptionPane.showInputDialog("What is your operand? ");
o = input.charAt(0);
}
}
Keep in mind that your users must be very sober, in order to avoid typos and receiving a NumberFormatException...

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

Categories

Resources