Last active
November 10, 2017 04:44
-
-
Save chasefloyd/e9ee7f0a4bab75a0d9f1d16256ad2b77 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Stack; | |
import java.util.Scanner; | |
public class Infix { | |
public static int evaluate(String expression) { | |
//char[] nextItem = expression.toCharArray(); | |
String[] nextItem = expression.split(" "); | |
Stack<Integer> operands = new Stack<>(); | |
Stack<String> operators = new Stack<>(); | |
for( int i = 0; i <= nextItem.length - 1; i ++) { | |
if(nextItem[i].charAt(i) >= '0' && nextItem[i].charAt(i) <= '9') { | |
operands.push((int)(nextItem[i].charAt(i))); | |
} | |
else { | |
double operand2 = operands.pop(); | |
double operand1 = operands.pop(); | |
double result = applyOperator(nextItem[i], operand1, operand2); | |
operands.push((int)result); | |
} | |
} | |
return operands; | |
} | |
public static double applyOperator(String string, double first, double second) { | |
if(string == "+") | |
return first + second; | |
//else if(string == "-") | |
//return first - second; | |
else if(string == "*") | |
return first * second; | |
else if(string == "/") { | |
if(second == 0) | |
throw new UnsupportedOperationException("Cant divide by 0"); | |
return first / second;} | |
else if(string == "^") | |
return Math.pow(first, second); | |
else | |
/*try { | |
throw new Exception("Invalid Operator"); | |
} catch (Exception e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
}*/ | |
return first - second; | |
} | |
public static void main(String[] args) { | |
Scanner input = new Scanner(System.in); | |
System.out.println("Please enter a expression: "); | |
String userInput = input.nextLine(); | |
System.out.println(evaluate(userInput)); | |
//evaluate(userInput); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment