if (first == 11)
{card1s = "Jack";
}else {
if (second == 11)
{card2s = "Jack";
} else {
if (third == 11)
{card3s = "Jack";
}
else {
if (fourth == 11)
{card4s = "Jack";
}
else {
if (fifth == 11)
{card5s = "Jack";
}
else {
if (first == 12)
{card1s = "Queen";
}
else {
if (second == 12)
{card2s = "Queen";
}
else {
if (third == 12)
{card3s = "Queen";
}
else {
if (fourth == 12)
{card4s = "Queen";
}
else {
if (fifth == 12)
{card5s = "Queen";
}
else {
if (first == 13)
{card1s = "King";
}
else {
if (second == 13)
{card2s = "King";
}
else {
if (third == 13)
{card3s = "King";
}
else {
if (fourth == 13)
{card4s = "King";
}
else {
if (fifth == 13)
{card1s = "King";
}
else {
if (first == 1)
{card1s = "Ace";
}
else {
if (second == 1)
{card2s = "Ace";
}
else {
if (third == 1)
{card3s = "Ace";
}
else {
if (fourth == 1)
{card4s = "Ace";
}
else {
if (fifth == 1)
{card5s = "Ace";
}
else {
card1s = null;
card2s = null;
card3s = null;
card4s = null;
card5s = null;
}}}}}}}}}}}}}}}}}}}}
if ((first >= 11) | (first == 1))
System.out.println("The first card is: " + card1s + first);
This is part of my poker game program that is used to translate card in words (ex. 11 is a Jack and 12 is a Queen), the result should be printing out the translated word along with the number that is used to determine the word. The program compiles without issue, but the problem is, when I run this program, it would come up with "The first card is: Jack13" or "Queen13" things like that.
You have a lot of duplicate code, and a switch is more apporpriate here. Also you should use methods. Example:
public static void main(String[] args) {
// ...
String card1s = getCardAsString(first);
// ...
if ((first >= 11) || (first == 1))
System.out.println("The first card is: " + card1s + first);
}
private static String getCardAsString(int i) {
switch (i) {
case 1:
return "Ace";
case 11:
return "Jack";
case 12:
return "Queen";
case 13:
return "King";
default:
return String.valueOf(i); // or return null; not sure what you need
}
}
With ifs:
private static String getCardAsString2(int i) {
if (i == 1)
return "Ace";
if (i == 11)
return "Jack";
if (i == 12)
return "Queen";
if (i == 13)
return "King";
return String.valueOf(i);// or return null;
}
Related
One of the requirements is a getMonthName method that returns the name if the month, i.e. January is 1. And a toString that returns the month name (String represesentation) , and I'm just worried that there's an easier way for what I'm doing than this:
import java.util.Scanner;
import java.io.*;
public class Month {
private int monthNum = 0;
private String monthName;
String monthOne = "JANUARY";
String monthTwo = "FEBRUARY";
String monthThree = "MARCH";
String monthFour = "APRIL";
String monthFive = "MAY";
String monthSix = "JUNE";
String monthSeven = "JULY";
String monthEight = "AUGUST";
String monthNine = "SEPTEMBER";
String monthTen = "OCTOBER";
String monthEleven = "NOVEMBER";
String monthTwelve = "DECEMBER";
//CONSTRUCTORS
public Month()
{
monthNum = 1;
}
public Month(int monthNum)
{
this.monthNum = monthNum;
if ((monthNum > 12) || (monthNum <1))
{
monthNum = 1;
}
}
public Month(String monthOne, String monthTwo, String monthThree, String monthFour, String monthFive, String monthSix, String monthSeven,
String monthEight, String monthNine, String monthTen, String monthEleven, String monthTwelve)
{
monthName.toUpperCase();
if (monthName.equals(monthOne))
{
monthNum = 1;
}
else if (monthName.equals(monthTwo))
{
monthNum = 2;
}
else if (monthName.equals(monthThree))
{
monthNum = 3;
}
else if (monthName.equals(monthFour))
{
monthNum = 4;
}
else if (monthName.equals(monthFive))
{
monthNum = 5;
}
else if (monthName.equals(monthSix))
{
monthNum = 6;
}
else if (monthName.equals(monthSeven))
{
monthNum = 7;
}
else if (monthName.equals(monthEight))
{
monthNum = 8;
}
else if (monthName.equals(monthNine))
{
monthNum = 9;
}
else if (monthName.equals(monthTen))
{
monthNum = 10;
}
else if (monthName.equals(monthEleven))
{
monthNum = 11;
}
else
{
monthNum = 12;
}
}
//METHODS
public void setMonthNum(int monthNum)
{
this.monthNum = monthNum;
if ((monthNum >12) || (monthNum<1))
{
monthNum = 1;
}
}
public int getMonthNumber()
{
return monthNum;
}
public String getMonthName()
{
if (monthNum == 1)
{
return "January";
}
else if (monthNum == 2)
{
return "February";
}
else if (monthNum == 3)
{
return "March";
}
else if (monthNum == 4)
{
return "April";
}
else if (monthNum == 5)
{
return "May";
}
else if (monthNum == 6)
{
return "June";
}
else if (monthNum == 7)
{
return "July";
}
else if (monthNum == 8)
{
return "August";
}
else if (monthNum == 9)
{
return "September";
}
else if (monthNum == 10)
{
return "October";
}
else if (monthNum == 11)
{
return "November";
}
else
{
return "December";
}
}
public String toString()
{
if (monthNum == 1)
{
return "January";
}
else if (monthNum == 2)
{
return "February";
}
else if (monthNum == 3)
{
return "March";
}
else if (monthNum == 4)
{
return "April";
}
else if (monthNum == 5)
{
return "May";
}
else if (monthNum == 6)
{
return "June";
}
else if (monthNum == 7)
{
return "July";
}
else if (monthNum == 8)
{
return "August";
}
else if (monthNum == 9)
{
return "September";
}
else if (monthNum == 10)
{
return "October";
}
else if (monthNum == 11)
{
return "November";
}
else
{
return "December";
}
}
}
Am I missing something or is this the best way at my level to do this?
If you must implement a Month class yourself then look into enums, otherwise
check out the docs for java.time.Month – Try something like this...
import java.time.Month;
public Month getMonthName( int monthNum )
{
return Month.of( monthNum );
}
Or simply...
System.out.println( Month.of( monthNumber ) );
Here are some suggestions to improve your class:
use KeyValuePair(example, map) to store the month list, since, it would be easy to maintain and retrieve information.
If you use keyValuePair collection you can access the month using id directly rather than using nested if statements.(as you did in getMonthName() and toString() method)
Another approach you could use is HashMap where key would be the month's number and value is its name. Using HashMap you can also get the key based on the value and vice-versa which seems you want to do.
Also try avoiding too much else ifs. You can use switch instead.
It is simply
class Month {
private static String monthNames[] = {
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"};
private int monthNumber;
public Month(int n) {
if (n < 1 || n > 12) {
monthNumber = 1;
} else {
monthNumber = n;
}
}
public String getMonthName() {
return monthNumber[monthNumber - 1];
}
#Override
public String toString() {
return getMonthName();
}
}
I am trying to write a program to convert an infix expression to a postfix expression.
The algorithm that I am using is as follows :
1. Create a stack
2. For each character t in the expression
- If t is an operand, append it to the output
- Else if t is ')',then pop from the stack till '(' is encountered and append
it to the output. do not append '(' to the output.
- If t is an operator or '('
-- If t has higher precedence than the top of the stack, then push t
on to the stack.
-- If t has lower precedence than top of the stack, then keep popping
from the stack and appending to the output until either stack is
empty or a lower priority operator is encountered.
After the input is over, keep popping and appending to the output until the
stack is empty.
Here is my code which prints out wrong results.
public class InfixToPostfix
{
private static boolean isOperator(char c)
{
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^'
|| c == '(' || c == ')';
}
private static boolean isLowerPrecedence(char op1, char op2)
{
switch (op1)
{
case '+':
case '-':
return !(op2 == '+' || op2 == '-');
case '*':
case '/':
return op2 == '^' || op2 == '(';
case '^':
return op2 == '(';
case '(':
return true;
default:
return false;
}
}
public static String convertToPostfix(String infix)
{
Stack<Character> stack = new Stack<Character>();
StringBuffer postfix = new StringBuffer(infix.length());
char c;
for (int i = 0; i < infix.length(); i++)
{
c = infix.charAt(i);
if (!isOperator(c))
{
postfix.append(c);
}
else
{
if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
{
postfix.append(stack.pop());
}
if (!stack.isEmpty())
{
stack.pop();
}
}
else
{
if (!stack.isEmpty() && !isLowerPrecedence(c, stack.peek()))
{
stack.push(c);
}
else
{
while (!stack.isEmpty() && isLowerPrecedence(c, stack.peek()))
{
Character pop = stack.pop();
if (pop != '(')
{
postfix.append(pop);
}
}
}
stack.push(c);
}
}
}
return postfix.toString();
}
public static void main(String[] args)
{
System.out.println(convertToPostfix("A*B-(C+D)+E"));
}
}
The program should print AB*CD+-E+ but it is printing AB*-CD+E.
Why is the output incorrect ?
Also, Is there a more elegant solution to this problem. Please share if you have or know one.
Issue is with your else part:
if (!stack.isEmpty() && !isLowerPrecedence(c, stack.peek()))
{
stack.push(c);
}
else
{
while (!stack.isEmpty() && isLowerPrecedence(c, stack.peek()))
{
Character pop = stack.pop();
if (pop != '(')
{
postfix.append(pop);
}
}
}
stack.push(c);
So here you are pushing the same c element twice with stack.push() when you see stack is not empty and precedence match is higher.
So put this stack.push within else part or remove the push from if condition.
Another issue is, when at the end you have some operators within the stack you dont pop them out.
Here's the code that i came up with for your case:
private static boolean isOperator(char c)
{
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^'
|| c == '(' || c == ')';
}
private static boolean isLowerPrecedence(char op1, char op2)
{
switch (op1)
{
case '+':
case '-':
return !(op2 == '+' || op2 == '-');
case '*':
case '/':
return op2 == '^' || op2 == '(';
case '^':
return op2 == '(';
case '(':
return true;
default:
return false;
}
}
public static String convertToPostfix(String infix)
{
Stack<Character> stack = new Stack<Character>();
StringBuffer postfix = new StringBuffer(infix.length());
char c;
for (int i = 0; i < infix.length(); i++)
{
c = infix.charAt(i);
if (!isOperator(c))
{
postfix.append(c);
}
else
{
if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
{
postfix.append(stack.pop());
}
if (!stack.isEmpty())
{
stack.pop();
}
}
else
{
if (!stack.isEmpty() && !isLowerPrecedence(c, stack.peek()))
{
stack.push(c);
}
else
{
while (!stack.isEmpty() && isLowerPrecedence(c, stack.peek()))
{
Character pop = stack.pop();
if (c != '(')
{
postfix.append(pop);
} else {
c = pop;
}
}
stack.push(c);
}
}
}
}
while (!stack.isEmpty()) {
postfix.append(stack.pop());
}
return postfix.toString();
}
public static void main(String[] args)
{
System.out.println(convertToPostfix("A*B-(C+D)+E"));
}
I think above answer is not correct.
This is the version corrected by me :
package Stack;
import java.util.Stack;
/*
*
Algorithm
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
…..3.1 If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty), push it.
…..3.2 Else, Pop the operator from the stack until the precedence of the scanned operator is less-equal to the precedence of the operator residing on the top of the stack. Push the scanned operator to the stack.
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘ is encountered.
6. Repeat steps 2-6 until infix expression is scanned.
7. Pop and output from the stack until it is not empty.
*/
public class InfixToPostFixEvalution {
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '(' || c == ')';
}
private static int getPrecedence(char ch) {
switch (ch) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
// A utility function to check if the given character is operand
private static boolean isOperand(char ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
public static String convertToPostfix(String infix) {
Stack<Character> stack = new Stack<Character>();
StringBuffer postfix = new StringBuffer(infix.length());
char c;
for (int i = 0; i < infix.length(); i++) {
c = infix.charAt(i);
if (isOperand(c)) {
postfix.append(c);
} else if (c == '(') {
stack.push(c);
}
// If the scanned character is an ‘)’, pop and output from the stack
// until an ‘(‘ is encountered.
else if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix.append(stack.pop());
}
if (!stack.isEmpty() && stack.peek() != '(')
return null;
else if(!stack.isEmpty())
stack.pop();
}
else if (isOperator(c)) // operator encountered
{
if (!stack.isEmpty() && getPrecedence(c) <= getPrecedence(stack.peek())) {
postfix.append(stack.pop());
}
stack.push(c);
}
}
while (!stack.isEmpty()) {
postfix.append(stack.pop());
}
return postfix.toString();
}
public static void main(String[] args) {
System.out.println(convertToPostfix("a+b*(c^d-e)^(f+g*h)-i"));
}
}
This code inserts the "(" as well in stack and removes accordingly. Just another way of implementing infix to postfix. Here the check is until I do not find lower priority operator in stack I will pop out the value. e.g if stack has - and next operator is +, it will pop - as it is of equal priority.
I have added custom stack implementation, however normal stack provide by java can also be used in place
import chapter4.LinkedListStack(custom stack implementation);
public class InfixToPostfix {
public String infixToPostfix(String str) {
LinkedListStack<String> stack = new LinkedListStack<>();
String[] st = str.split("");
String result = "";
for (String s : st) {
if (operator(s)) {
if (")".equals(s)) {
while (!stack.isEmpty() && !"(".equals(stack.getTop())) {
result += stack.pop();
}
if (!stack.isEmpty()) {
stack.pop();
}
} else {
if (!stack.isEmpty() && !isLowerPrecedence(s, stack.getTop())) {
stack.push(s);
} else {
while (!stack.isEmpty() && isLowerPrecedence(s, stack.getTop())) {
String top = stack.pop();
if (!"(".equals(top)) {
result += top;
}
}
stack.push(s);
}
}
} else {
result += s;
}
}
while (!stack.isEmpty()) {
result += stack.pop();
}
return result;
}
private boolean isLowerPrecedence(String s, String s1) {
switch (s) {
case "+":
return !("+".equals(s1) || "(".equals(s1));
case "-":
return !("-".equals(s1) || "(".equals(s1));
case "*":
return "/".equals(s1) || "^".equals(s1) || "(".equals(s1);
case "/":
return "*".equals(s1) || "^".equals(s1) || "(".equals(s1);
case "^":
return "(".equals(s1);
case "(":
return false;
default:
return false;
}
}
private boolean operator(String s) {
return "+".equals(s) || "-".equals(s) || "*".equals(s) || "/".equals(s) || "^".equals(s) || "(".equals(s) ||
")".equals(s);
}
public static void main(String[] args) {
InfixToPostfix itp = new InfixToPostfix();
System.out.println("The Postfix expression for A*B-(C+D)+E is: " + itp.infixToPostfix("A*B-(C+D)+E"));
System.out.println("The Postfix expression for 1+2*4/5-7+3/6 is: " + itp.infixToPostfix("1+2*4/5-7+3/6"));
System.out.println("The Postfix expression for a+(b*c)/d is: " + itp.infixToPostfix("a+(b*c)/d"));
}
}
public class LinkedListStack<E> {
private Node<E> head;
private static class Node<E> {
E item;
Node<E> next;
public Node(E item, Node<E> next) {
this.item = item;
this.next = next;
}
}
public void push(E item) {
System.out.println("push: " + item);
Node<E> newNode = new Node<>(item, null);
newNode.next = head;
head = newNode;
}
public E pop() {
if (isEmpty()) {
System.out.println("stack is Empty -> empty stack exception");
return null;
}
System.out.println("pop: " + head.item);
E data = head.item;
head = head.next;
return data;
}
public boolean isEmpty() {
return head == null;
}
public E getTop() {
return head.item;
}
}
I think the problem is here:
private static boolean isLowerPrecedence(char op1, char op2)
{
switch (op1)
{
.....
case '(':
return true;
.....
}
In the case '(', false should be returned.
This solution requires proper braces around the original expression, but its quite simple and straight forward compared to other answers I looked at. Just for someone who might need it because the post is an old post.
public static String InfixToPostfix(String origin)
{
String[] params = origin.split(" ");
Stack<String> ops = new Stack<>();
Stack<String> vals = new Stack<>();
for (int i = 0; i < params.length; i++)
{
switch (params[i]) {
case "(":
;
break;
case "+":
ops.push(params[i]);
break;
case "-":
ops.push(params[i]);
break;
case "*":
ops.push(params[i]);
break;
case "/":
ops.push(params[i]);
break;
case "sqrt":
ops.push(params[i]);
break;
// Token not operator or paren: push double value.
case ")":
String d1 = vals.pop();
String d2 = vals.pop();
String op = ops.pop();
vals.push("( " + d2 + " " + d1 + " "+ op + " )");
break;
default:
vals.push(params[i]);
break;
}
}
// System.out.print(vals.pop());
return vals.pop();
}
Here's a method I wrote to check which operator has the highest precedence, now my question is: is there any other way I can do this? I have been testing this one and it works fine, but I'm pretty sure there should be room for improvement. What do you think?
static boolean hasHigherPrecendence(char top, char current){
String t = String.valueOf(top);
String c = String.valueOf(current);
System.out.println(t);
System.out.println(c);
switch (t) {
case "-":
if ( c.equals("-") || c.equals("+") )
return false;
break;
case "+":
if ( c.equals("-") || c.equals("+") )
return false;
break;
case "/":
if ( !c.equals("*") || !c.equals(t) || !c.equals("%") )
return false;
break;
case "*":
if ( !c.equals("%") || !c.equals(t) || !c.equals("/"))
return false;
break;
case "%":
if (c.equals(t) || c.equals("*") || c.equals("/"))
return false;
break;
default:
throw new IllegalArgumentException("Operator unknown: " + t);
}
return true;
}
If it were me I would rank the operators in a function (note, the values I chose are not necessarily the ones you should use ...):
private static final int rankOperator(char op) {
switch (op) {
case '-' : return 0;
case '+' : return 0;
case '/' : return 2;
case '*' : return 2;
case '%' : return 4;
}
throw new IllegalStateException("Unknown operator " + op);
}
public boolean hasHigherPrecedence(char top, char current) {
return rankOperator(top) > rankOperator(current);
}
Apart of using maps, arrays, functions... you can reduce your code using the concatenating the cases with the same behaviour:
static boolean hasHigherPrecendence(char top, char current){
String t = String.valueOf(top);
String c = String.valueOf(current);
System.out.println(t);
System.out.println(c);
switch (t) {
case "-":
case "+":
if ( c.equals("-") || c.equals("+") )
return false;
break;
case "/":
case "*":
case "%":
if (c.equals("%") || c.equals("*") || c.equals("/"))
return false;
break;
default:
throw new IllegalArgumentException("Operator unknown: " + t);
}
return true;
}
static boolean hasHigherPrecendence(char top, char current){
Map<Character,Integer> map = new HashMap<>();
map.put('+',new Integer(1));
map.put('-',new Integer(1));
map.put('*',new Integer(2));
map.put('/',new Integer(2));
map.put('%',new Integer(3));
if( map.get(top)==null ){
throw new IllegalArgumentException("Operator unknown: " + top);
}
if( map.get(current)==null ){
throw new IllegalArgumentException("Operator unknown: " + current);
}
if(map.get(t) >= map.get(c)){
return true;
}else{
return false;
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am a high school student currently taking an introductory computer science course. In class we were assigned with creating a program that would take user input for card notation and return the full description of the card. For example, A user who inputs "AS" would see "Ace of Spades" in the terminal window. However, when my code executes, I get a "null of null" instead of "Ace of Spades" or another card notation.
public class Card
{
private String rank;
private String suit;
private String fullRank;
private String fullSuit;
public Card(String rankAndSuit)
{
rank = rankAndSuit.substring(0,1);
if (rank == "A")
{
fullRank = "Ace";
}
else
if (rank == "2")
{
fullRank = "2";
}
else
if (rank == "3")
{
fullRank = "3";
}
else
if (rank == "4")
{
fullRank = "4";
}
else
if (rank == "5")
{
fullRank = "5";
}
else
if (rank == "6")
{
fullRank = "6";
}
else
if (rank == "7")
{
fullRank = "7";
}
else
if (rank == "8")
{
fullRank = "8";
}
else
if (rank == "9")
{
fullRank = "9";
}
else
if (rank == "10")
{
fullRank = "10";
}
else
if (rank == "J")
{
fullRank = "Jack";
}
else
if (rank == "Q")
{
fullRank = "Queen";
}
else
if (rank == "K")
{
fullRank = "King";
}
suit = rankAndSuit.substring(1,2);
if (suit == "D")
{
fullSuit = "Diamonds";
}
else
if (suit == "H")
{
fullSuit = "Hearts";
}
else
if (suit == "S")
{
fullSuit = "Spades";
}
else
if (suit == "C")
{ fullSuit = "Clubs";
}
}
public String getCardDescription()
{
return fullRank + " of " + fullSuit;
}
}
My Tester Class is :
public class CardTester
{
public static void main(String[] args)
{
Card testCard = new Card("AS");
String cardDescription = testCard.getCardDescription();
System.out.print(cardDescription);
}
}
What is causing me to get null?
You're committing a cardinal sin of string comparison in Java.
See this question: How do I compare strings in Java?
You're comparing strings using ==:
rank == "5"
Don't. Use:
if("5".equals(rank)){
instead. The order (as opposed to if(rank.equals("5")) ensures there is no null pointer exception if the string you were comparing was ever to be null.
I cant seem to get the inside of the try block to make stacks, I am meant to get a calculator with single digit by using stacks inside the try block. The inside of the try block is giving me emptystackexception
import java.util.EmptyStackException;
import java.util.*;
public class Infix
{
public static void main(String[] args){
System.out.println(evaluateInfix("1*2*3"));
}
public static double evaluateInfix(String infix)
{
try
{
Stack<Character> valueStack = new Stack<Character> ();
Stack<Character> operatorStack = new Stack<Character> ();
double result;
for(char ch: infix.toCharArray()){
if(ch >= 0 && ch <= 9){
valueStack.push(ch);
} else if(ch == '('){
operatorStack.push(ch);
} else if(ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%' || ch == '^' || ch == '='){
if(operatorStack.isEmpty()){
operatorStack.push(ch);
} else if(precedence(ch) > precedence(operatorStack.peek())){
operatorStack.push(ch);
} else {
while(!operatorStack.isEmpty() && precedence(ch) <= precedence(operatorStack.peek())){
result = compute(valueOf(valueStack.pop()), valueOf(valueStack.pop()), operatorStack.pop());
valueStack.push((char)result);
}
operatorStack.push(ch);
}
} else if(ch == ')'){
while(operatorStack.peek() != '('){
result = compute(valueOf(valueStack.pop()), valueOf(valueStack.pop()), operatorStack.pop());
valueStack.push((char)result);
}
operatorStack.pop();
}
}
while(!operatorStack.isEmpty()){
result = compute(valueOf(valueStack.pop()), valueOf(valueStack.pop()), operatorStack.pop());
valueStack.push((char)result);
}
result = valueStack.peek();
System.out.println(result);
/* **********
Task 3
complete this section to calculate the infix expression
*/
} //end try
catch (EmptyStackException e)
{
/* **********
Task 3
complete this to return Double.NaN
*/
}
catch (ArithmeticException e)
{
/* **********
Task 3
complete this to return Double.NEGATIVE_INFINITY
*/
}
return 3.0;
} // end evaluateInfix
private static int precedence(char operator)
{
switch(operator){
case '(': case ')': return 0;
case '+': case '-': return 1;
case '*': case '/': case '%': return 2;
case '^': return 3;
case '=': return 4;
}
return -1;
}
private static double valueOf(char variable)
{
switch (variable)
{
case '1': return 1.0;
case '2': return 2.0;
case '3': return 3.0;
case '4': return 4.0;
case '5': return 5.0;
case '6': return 6.0;
case '7': return 7.0;
case '8': return 8.0;
case '9': return 9.0;
case '0': return 0.0;
} // end switch
return 0;
} // end valueOf
private static Double compute(Double operandOne, Double operandTwo, char operator)
{
if(operator == '+'){
return operandOne + operandTwo;
} else if(operator == '-'){
return operandOne - operandTwo;
} else if(operator == '*'){
return operandOne * operandTwo;
} else if(operator == '/'){
return operandOne / operandTwo;
} else if(operator == '%'){
return operandOne % operandTwo;
} else if(operator == '^'){
return Math.pow(operandOne, operandTwo);
} else {
return null;
}
} // end compute
} // end Infix
Shouldn't the first if contain '' around the numbers?
if(ch >= '0' && ch <= '9'){
You have a redundant pair of "}" and "{" which turn the bulk of your code into an initialization block - essentially a constructor of the Infix class.
(Based on your comment) - there is a missing method declaration.
Try changing the first few lines from:
public class Infix {
public static void main(String[] args){
System.out.println(evaluateInfix("1*2*3"));
}
{
try {
...
to:
public class Infix {
public static void main(String[] args){
System.out.println(evaluateInfix("1*2*3"));
}
public static double evaluateInfix(String infix) {
try {
...