Okay... I think I might have gone over my head with trying to simplify this code. I place operators such as ( *, +, /, -) in a split. Know i want to call them individually to do their perspective task in a if (operators.equals.(+)){
return num1 + num2. }
then for *, -, / perspectively
how can i do that correctly having using math in my earlier code:
String function = "[+\\-*/]+"; //this
String[] token = input.split(function);//and this
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[1]);
double answer;
String operator = input.toCharArray()[token[0].length()]+"";
if (operator.matches(function) && (token[0]+token[1]+operator).length()==input.length()) {
System.out.println("Operation is " + operator+ ", numbers are " + token[0] + " and " + token[1]);
} else {
System.out.println("Your entry of " + input + " is invalid");
}
You don't.
String.split only returns the parts of the String that were not matched. If you want to know the matched code, you need to use a more sophisticated regular expression, i.e. the Pattern and Matcher classes, or write your own String tokenization class yourself.
In this example Token is a class you make yourself):
public List<Token> generateTokenList(String input) {
List<Token> = new LinkedList<>();
for(char c : input.toCharArray()) {
if(Character.isDigit(c)) {
// handle digit case
} else if (c == '+') {
// handle plus
} else if (c == '-') {
// handle minus
} else {
/* you get the idea */
}
}
}
There are libraries that do this for you, such as ANTLR but this sounds like a school assignment so you probably have to do this the hard way.
Change your if body to something like
if (operator.matches(function) &&
(token[0] + token[1] + operator).length() == input.length())
{
double result = 0;
if (operator.equals("+")) {
result = num1 + num2;
} else if (operator.equals("-")) {
result = num1 - num2;
} else if (operator.equals("*")) {
result = num1 * num2;
} else if (operator.equals("/")) {
result = num1 / num2;
}
System.out.printf("%.2f %s %.2f = %.2f%n", num1, operator, num2,
result);
}
And your code works as expected.
Related
I recently made a calculator and everything is working fine except for the equal button. While it is outputting the right answer, I would like to keep using operator even after pressing equals. How can I do that?
if(e.getSource() == btnEquals) {
num2 = 0;
char operator2 = 's';
try {
display.append("=" + "\n");
for ( String line : display.getText().split("\\n")) {
char operator1 = line.charAt(line.length()-1);
num1 = Double.parseDouble(line.substring(0, line.length()-1));
if (operator2 == 's') {
num2 = num1;
operator2 = operator1;
} else if (operator2 == '+') {
num2 = num2 + num1;
operator2 = operator1;
} else if (operator2 == '-') {
num2 = num2 - num1;
operator2 = operator1;
} else if (operator2 == '*') {
num2 = num2 * num1;
operator2 = operator1;
} else if (operator2 == '/') {
num2 = num2 / num1;
operator2 = operator1;
}
}
} catch (NumberFormatException a) {
display.setText("Error: Consecutive Operators " + " (=) " + " or no input" + "\n");
return;
}
display.setText(display.getText() + num2);
}
}
When you press the button (I assume it is a Swing JButton) all the work is done in a specific thread of execution which is called event dispatch thread. As the name implies it is not the right thread for doing the heavy lifting, i.e. your current work. While you are using it it can't dispatch events for other GUI elements so you can't use any other elements.
So you need to put your business work into an extra thread and thus deal with concurrency in Swing. You can read about it here.
Wrap it with while(True) statement and will run till the exit.
I have the following pseudocode and need to write a java method to evaluate a prefix expression:
Algorithm valueOfPrefixExpression(prefixExpression)
Input: a valid positive-integer arithmetic expression in prefix form
Return value: the value of the prefix expression
if next token is an integer
return the integer
else
Read an operator, say op
firstOperand gets valueOfPrefixExpression(remainingExpression)
secondOperand gets valueOfPrefixExpression(remainingExpression)
return firstOperand op secondOperand
endif
How can I write this method? I tried this and I think it could be right but I am getting a "missing return statement" error so I can't compile. Assume method is only called if args has 1 or more elements. (no empty arrays)
public static int prefixAlgorithm(String[] args) {
for (int i = 0; i < args.length; i++) {
if (!args[i].equals("+") && !args[i].equals("-")
&& !args[i].equals("*") && !args[i].equals("/")) {
int operand = parseInt(args[i]);
return operand;
} else {
int firstOperand = prefixAlgorithm(Arrays.copyOfRange(args, i, (args.length - 1)));
int secondOperand = prefixAlgorithm(Arrays.copyOfRange(args, i, (args.length - 1)));
if (args[i].equals("+")) {
return firstOperand + secondOperand;
} else if (args[i].equals("-")) {
return firstOperand - secondOperand;
} else if (args[i].equals("*")) {
return firstOperand * secondOperand;
} else if (args[i].equals("/")) {
return firstOperand / secondOperand;
}
}
}
}
PrefixEvaluator with input and Scanner:
import java.util.*;
public class PrefixEvaluator {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("This program evaluates prefix expressions");
System.out.println("for operators +, -, *, / and %");
System.out.print("expression? ");
System.out.println("value = " + evaluate(console));
}
// pre : input contains a legal prefix expression
// post: expression is consumed and the result is returned
public static double evaluate(Scanner input) {
if (input.hasNextDouble()) {
return input.nextDouble();
} else {
String operator = input.next();
double operand1 = evaluate(input);
double operand2 = evaluate(input);
return evaluate(operator, operand1, operand2);
}
}
// pre : operator is one of +, -, *, / or %
// post: returns the result of applying the given operator to
// the given operands
public static double evaluate(String operator, double operand1,
double operand2) {
if (operator.equals("+")) {
return operand1 + operand2;
} else if (operator.equals("-")) {
return operand1 - operand2;
} else if (operator.equals("*")) {
return operand1 * operand2;
} else if (operator.equals("/")) {
return operand1 / operand2;
} else if (operator.equals("%")) {
return operand1 % operand2;
} else {
throw new RuntimeException("illegal operator " + operator);
}
}
}
PrefixEvaluator with no input and queue:
import java.util.*;
public class PrefixEvaluator {
public static void main(String[] args) {
String input = "- * + 4 3 2 5";
String[] expression = input.split ( " " );
Queue<String> expressionQueue = new LinkedList<String>();
for (String element : expression)
{
expressionQueue.add ( element );
}
System.out.println("value = " + evaluate(expressionQueue));
}
// pre : input contains a legal prefix expression
// post: expression is consumed and the result is returned
public static double evaluate(Queue <String> input) {
if(input.peek ( ) != null && input.peek ( ).matches ( "^(-?)\\d+$" ))
{
return Long.parseLong ( input.poll ( ) );
}
else
{
String operator = input.poll();
double operand1 = evaluate(input);
double operand2 = evaluate(input);
return evaluate(operator, operand1, operand2);
}
}
// pre : operator is one of +, -, *, / or %
// post: returns the result of applying the given operator to
// the given operands
public static double evaluate(String operator, double operand1,
double operand2) {
if (operator.equals("+")) {
return operand1 + operand2;
} else if (operator.equals("-")) {
return operand1 - operand2;
} else if (operator.equals("*")) {
return operand1 * operand2;
} else if (operator.equals("/")) {
return operand1 / operand2;
} else if (operator.equals("%")) {
return operand1 % operand2;
} else {
throw new RuntimeException("illegal operator " + operator);
}
}
}
I/O Example:
This program evaluates prefix expressions
for operators +, -, *, / and %
expression? - * + 4 3 2 5
value = 9.0
Documentation:
Queues: Queue (Java Platform SE 7 )
Patterns: Pattern (Java Platform SE 7 )
Your compilation problem is because you don't have a guaranteed return from the method. If arg[i] is something other than one of the four expected characters for the entire array, you'll simply run off the bottom of the function.
You may believe that the input will always conform to expectations, but compilerse know better than to trust humans. :-)
I'm supposed to implement 3 functions in the following code.
Functions:
1. evaluate arithmetic expression in postfix
2. convert arithmetic expression from infix to postfix
3. convert arithmetic expression from postfix to infix
I don't know at all where I could start and how the functions need to look / made up at all. If you could help me with just one of these 3 functions, I would probably be able to do the other 2 myself.
Here is the code:
import java.util.Stack;
public class Postfix {
public static int evalPostfix(String postfix) {
// TODO
}
public static String infixToPostfix(String infix) {
// TODO
}
public static String postfixToInfix(String postfix) {
// TODO
}
public static void main(String[] args) {
String infix1 = "(3-(7*2))";
String postfix1 = "372*-";
int eval1 = -11;
String infix2 = "((7+1)*((3-6)*(5-2)))";
String postfix2 = "71+36-52-**";
int eval2 = -72;
System.out.println(" postfix1: " + postfix1);
int n = evalPostfix(postfix1);
System.out.println("evalPostfix(postfix1): " + n);
if (n == eval1) {
System.out.println(" Right!");
} else {
System.out.println(" Wrong!");
}
System.out.println();
System.out.println(" infix1: " + infix1);
String s = infixToPostfix(infix1);
System.out.println("infixToPostfix(infix1): " + s);
if (s.equals(postfix1)) {
System.out.println(" Right!");
} else {
System.out.println(" Wrong!");
}
System.out.println();
System.out.println(" postfix1: " + postfix1);
s = postfixToInfix(postfix1);
System.out.println("postfixToInfix(postfix1): " + s);
if (s.equals(infix1)) {
System.out.println(" Right!");
} else {
System.out.println(" Wrong!");
}
System.out.println();
System.out.println(" postfix2: " + postfix2);
n = evalPostfix(postfix2);
System.out.println("evalPostfix(postfix2): " + n);
if (n == eval2) {
System.out.println(" Right!");
} else {
System.out.println(" Wrong!");
}
System.out.println();
System.out.println(" infix2: " + infix2);
s = infixToPostfix(infix2);
System.out.println("infixToPostfix(infix2): " + s);
if (s.equals(postfix2)) {
System.out.println(" Right!");
} else {
System.out.println(" Wrong!");
}
System.out.println();
System.out.println(" postfix2: " + postfix2);
s = postfixToInfix(postfix2);
System.out.println("postfixToInfix(postfix2): " + s);
if (s.equals(infix2)) {
System.out.println(" Right!");
} else {
System.out.println(" Wrong!");
}
System.out.println();
}
}
Here is some incomplete pseudocode to help you:
function int evalPostfix(string postfix)
repeat
// Fetch the next item.
item <- get next item from postfix
// Process the current item.
if (item is operand)
push item onto stack
else if (item is operator)
pop required number of operands from the stack
push operator(operands) onto stack
else
throw error "Unrecognised item: " + item + " found."
end if
until (no more items in postfix)
return pop from stack
end function
You will need separate operator functions for each operator that your code needs to deal with.
This is a classic 'Stack' data structure problem.
May be you have already given it a try with Stacks (you have a stack import.), you can also solve that with regular expressions or binary trees etc,
in case you just want an idea to solve that, hope this may help:
infix to postfix conversion with stacks:
Algorithm:
Scan the input infix expression from left to right.
If that's an operand add it to your temporary string.
else if the order of precedence of the operator is more than the operator in stacks or stack is empty then push it to stack.
If it is '(', add that to stack.
else if it is ')', pop and add item to output string until an '(' comes.
keep doing 2-5 util string have more characters.
static Stack<String> stack;
private static String doInfixToPostfix(String exp) {
stack = new Stack<String>();
String output = "";
for(int i=0;i<exp.length();i++){
if(exp.charAt(i) == '('){
stack.push("(");
}
else if(exp.charAt(i) == ')'){
while(stack.size()>0 && stack.peek() != "("){
output+= stack.pop();
}
if(stack.size()>0 && stack.peek() != "(")
return "INVALID";
else
stack.pop();
}
else if(isOperand("" + exp.charAt(i))){
//Its a Number
//It could be replaced to get more than one digits.....
output+= exp.charAt(i);;
}
else{
//Its a operator
while(stack.size()>0 && (priority("" + exp.charAt(i)) < priority(stack.peek()))){
output += stack.pop();
}
stack.push("" + exp.charAt(i));
}
}
while(stack.size()>0){
output+=stack.pop();
}
return output;
}
private static int priority(String value) {
if(value == "+" || value == "-") return 1;
else if(value == "*" || value == "/") return 2;
else if(value == "^") return 3;
return 0;
}
//This could be modified to accept more than one digits...
private static boolean isOperand(String value) {
try{
Integer.parseInt(value);
}
catch(NumberFormatException e){return false;}
return true;
}
and hey, instead comparing outputs by those very long code blocks, you could have simply used assertEquals() test cases.
I am experiencing trouble in the creation of my reverse polish notation calculator with my validation code. I need the calculator to accept the two shift operators (<< and >>) as part of the calculations. The following snippets of code is the validation part and also the calculation.
public static boolean isInt(String userinput) {
try {
Integer.parseInt(userinput); // Try to parse. Makes sure that the values entered are actual numbers
return true; // Boolean value to show if the equation entered is valid or not
} catch (NumberFormatException e) {
System.out.println("Please enter a valid expression!");
invalidlines++;
return false;
}
}
public static boolean isValidLine(String line) {
line = line.trim();
if (line.length() <= 4) { // Trims the lines down to 4 and ensures there is no spaces being included
return false;
} else {
String[] calcarray = new String[3];
calcarray = line.split(" ");
String operators = new String("[+\\-\\*\\/\\<<\\>>\\%\\&\\|]"); // Validator using regular expressions to check the operator used
if (isInt(calcarray[0].toString()) && isInt(calcarray[1].toString()) && calcarray[2].matches(operators)) { // Checks that the operator in the string matches the ones in the regular expression
return true;
} else {
return false;
}
}
}
below is the calculator part:
String keyboardInput = new String();
Scanner kbScan = new Scanner(System.in);
int answer = 0;
while (true) {
display("Please enter an equation");
keyboardInput = kbScan.nextLine();
if (isValidLine(keyboardInput)) {
String[] equation = new String[3]; // We know that this is only going to contain 3 to be valid
equation = keyboardInput.split(" "); // split this up, as it's stored with the spaces.
int num1 = Integer.parseInt(equation[0]);
int num2 = Integer.parseInt(equation[1]);
switch (equation[2]) { // This case switch checks the third position of the
// string to decide which operator is being used. It then works out the
// answer and breaks to the next instruction
case ("+"):
answer = num1 + num2;
break;
case ("-"):
answer = num1 - num2;
break;
case ("/"):
answer = num1 / num2;
break;
case ("*"):
answer = num1 * num2;
break;
case ("<<"):
answer = num1 << num2;
break;
case (">>"):
answer = num1 >> num2;
break;
case ("%"):
answer = num1 % num2;
break;
case ("|"):
answer = num1 | num2;
break;
case ("&"):
answer = num1 & num2;
break;
}
display("Your post fix expression: " + equation[0] + " " + equation[1] + " " + equation[2]);
display("Your calculation: " + equation[0] + " " + equation[2] + " " + equation[1] + " = " + answer);
} else {
display("The equation you entered is invalid");
}
}
Whenever a valid expression is entered the following error is shown in the console:
Enter F for file calculator or K for keyboard input
k
Please enter an equation
10 2 <<
The equation you entered is invalid
Please enter an equation
And I cannot figure out which part of my validation is wrong for these expressions.
Problem is with your operators regex.
User rather something like:
("\\+|\\-|\\*|\\/|<<|>>|\\%|\\&|\\|")
import java.util.Scanner;
public class Improved {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number operaion number: ");
int operand1 = Integer.parseInt(input.nextLine());
char expo1 = input.next().charAt(0);
int operand2 = Integer.parseInt(input.nextLine());
System.out.println( operand1 + expo1 + operand2 + "=");
if ( expo1 == '/' && operand2 == '0' ){
System.out.println("Cannot divide by zero"); }
else
if (expo1 == '-') {
System.out.println(operand1-operand2);
} else
if (expo1 == '+') {
System.out.println(operand1+operand2);
} else
if (expo1 == '/') {
System.out.println(operand1/operand2);
} else
if (expo1 == '%') {
System.out.println(operand1%operand2);
}
else{
System.out.println(" Error.Invalid operator.");
}
}
}
//This bottom works, but I found out that this is not what is supposed to be done with this problem
/*
public class Else {
public static void main(String[] args) {
int operand1;
char exp1;
int operand2;
if (args.length != 3 ) {
System.err.println("*** Program needs 3 arguements***");
System.err.println("Usage: java Else int1 exp int2");
System.exit(1);
}
operand1 = Integer.parseInt(args[0]);
exp1 = args[1].charAt(0);
operand2 = Integer.parseInt(args[2]);
System.out.print(args[0] + args[1] + args[2] + "=");
if(exp1 == '-') {
System.out.println(operand1 - operand2);
} else
if (exp1 == '+') {
System.out.println(operand1 + operand2);
} else
if (exp1 == '/') {
System.out.println(operand1 / operand2);
} else
if (exp1 == '%') {
System.out.println(operand1 % operand2);
}
else{
System.out.println(" Error.Invalid operator.");
}
}
}
*/
What I want the program to do is ask one to enter a math operation 1/2 or 1%2 (not multiplication)
, but just like that without spaces. Still, I want to check which operation is being done which is why i put the if statements. What I don't get is how the program would know when an operation appears in a string. I'm not even sure if I set it correctly. Overall, I want a string that reads the number then the operation an then the number again. I'm sorry if this seems like doing my hw, but I have tried making this program multiple times, but can't understand how I can do this with a string. I wrote the second one to show that I have done this multiple times, so you can ignore it. Thank You very much!
read input as a String using:
String inputString = input.nextLine();
get the index of the operator:
int indexOp = inputString.indexOf("+");
if(indexOp < 0) indexOp = inputString.indexOf("-"); //cannot find +, so find -
if(indexOp < 0) indexOp = inputString.indexOf("/"); //cannot find -, so find /
if(indexOp < 0) indexOp = inputString.indexOf("%"); //cannot find /, so find %
get the first and second operand with:
int operand1 = Integer.parseInt(inputString.substring(0,indexOp));
int operand2 = Integer.parseInt(inputString.substring(indexOp+1,inputString.length());
get the operator from the indexOp we got earlier:
char operator = inputString.charAt(indexOp);
Hope it helps :)
I have no doubt there are a number of ways this might be achieved, this is simply another example...
What this tries to do, is break down the incoming text into groups of digits and non digits. It then loops through these groups making up the various elements of the calculation...
Scanner input = new Scanner(System.in);
System.out.println("Enter a number operaion number: ");
String text = input.nextLine();
System.out.println("Input = " + text);
text = text.replaceAll("\\s", "");
System.out.println("Parse = " + text);
Pattern p = Pattern.compile("\\d+|\\D+");
Matcher m = p.matcher(text);
int index = 0;
int op1 = -1;
int op2 = -2;
String exp1 = "";
while (index < 3 && m.find()) {
System.out.println(index);
String part = m.group();
switch (index) {
case 0:
op1 = Integer.parseInt(part);
break;
case 2:
op2 = Integer.parseInt(part);
break;
case 1:
exp1 = part;
break;
}
index++;
}
System.out.println(op1 + " " + exp1 + " " + op2);
What this does have, is the power to to allow you to supply a much longer calculation, for example 20+30/40-50...etc.
You would need to park each operand and exponent into some kind of List and extract them as you need them...or you could actually do the calculation directly within the while loop
Try this:
package week11;
import java.util.Scanner;
public class maths {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("enter a number ");
int x = scanner.nextInt();
System.out.println("put +, -, / or * ");
char expo1 = scanner.next().charAt(0);
System.out.println("second number please ");
int y = scanner.nextInt();
System.out.println( "Answer is" + ":");
if ( expo1 == '/' && y == '0' ){
System.out.println("cannot be divided by 0"); }
else
if (expo1 == '-') {
System.out.println(x-y);
} else
if (expo1 == '+') {
System.out.println(x+y);
} else
if (expo1 == '/') {
System.out.println(x/y);
} else
if (expo1 == '%') {
System.out.println(x%y);
}
else{
System.out.println(" Error!");
}
}
}
I would like to add another solution, which removes a lot of the parsing work.
import java.util.Scanner;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
class Scratch {
public static void main(String[] args) throws ScriptException {
System.out.println("Enter an operation:");
Scanner input = new Scanner(System.in);
String operation = input.nextLine();
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = engine.eval(operation);
System.out.printf("%s = %s%n", operation, result);
}
}
sample result
Enter an operation:
2 + 3 * 4
2 + 3 * 4 = 14.0