Evaluateeg
EvaluateInFix.java:
import java.util.Stack;
import java.util.Scanner;
public class EvaluateInfix
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("This program an inFix Expression: ");
System.out.print("Enter an inFix Expression that you want to
evaluate (or enter ! to exit): ");
String aString = keyboard.nextLine();
while (!aString.equals("!"))
{
System.out.println (evaluateinFix(aString));
System.out.print("Enter an inFix Expression that you
want to evaluate (or enter ! to exit): ");
aString = keyboard.nextLine();
} // end while
}
//For testing, try these expressions/results
// (5 * 7 + 1) * 6 / (2 ^ 3 - 3 * 4 + 1) = -72
// (2 + 3) / (4 - 5 ) - 5 = 10
// Avoid testing double digit within the expression for now
public static String evaluateinFix(String inFix)
{
Stack<Character>
operatorStack = new Stack<Character>();
Stack<Integer> valueStack =
new Stack<Integer>();
/////////////////////////////////////////////////////////////////////
//TO DO: ADD CODE HERE BY
CONVERTING ALGORITHM ON PAGE 172 OF BOOK //
/////////////////////////////////////////////////////////////////////
return
valueStack.peek().toString();
}
//Evaluates expression like 2+3 and returns the result like 5
public static int evaluateOperation(char operator, int operandOne,
int operandTwo)
{
System.out.println(operandOne + " " + operator + " " +
operandTwo);
switch (operator)
{
case '^':
return (int)Math.pow(operandOne,
operandTwo);
case
'+':
return operandOne + operandTwo;
case '-':
return operandOne - operandTwo;
case '*':
return operandOne * operandTwo;
case '/':
if (operandTwo == 0)
{throw new UnsupportedOperationException("Cannot
divide by zero.");}
return operandOne / operandTwo;
}
return 0;
}
//Returns true if precedence of Operator1 is less than precedence
of Operator2
public static boolean checkPrecedence(char Operator1, char
Operator2)
{
if (Operator2 == '(' || Operator2 == ')')
return false;
if ((Operator1 == '*' || Operator1 == '/') && (Operator2 ==
'+' || Operator2 == '-'))
return false;
else
return true;
}
}
A3_Book_Page172_Algorithm:
Algorithm evaluateInfix(infix)
// Evaluates an infix expression.
operatorStack = a new empty stack
valueStack = a new empty stack
while (infix has characters left to process) {
nextCharacter = next nonblank character of infix
switch (nextCharacter) {
case variable:
valueStack.push(value of the variable nextCharacter)
break
case '^':
operatorStack.push(nextCharacter)
break
case '+':
case '-':
case '*':
case '/':
while (!operatorStack.isEmpty() and precedence of nextCharacter
<= precedence of operatorStack.peek()) {
// Execute operator at top of operatorStack
topOperator = operatorStack.pop()
operandTwo = valueStack.pop()
operandOne = valueStack.pop()
result = the result of the operation in topOperator and its
operands
operandOne
and operandTwo
valueStack.push(result)
}
operatorStack.push(nextCharacter)
break
case '(':
operatorStack.push(nextCharacter)
break
case ')': // Stack is not empty if infix expression is valid
topOperator = operatorStack.pop()
while (topOperator != '(') {
operandTwo = valueStack.pop()
operandOne = valueStack.pop()
result = the result of the operation in topOperator and its
operands
operandOne
and operandTwo
valueStack.push(result)
topOperator = operatorStack.pop()
}
break
NOTE : -
ALWAYS MAKE SURE THAT EVERY CHARACTER OF EXPRESSION IS SEPERATED BY SPACE
I.E DO NOT INPUT EXPRESSION LIKE (2 + 3) * 2 INSTEAD IT SHOULD BE ( 2 + 3 ) * 2
SOURCE CODE
public static String evaluateinFix(String inFix)
{
Stack<Character> operatorStack = new Stack<Character>();
Stack<Integer> valueStack = new Stack<Integer>();
/////////////////////////////////////////////////////////////////////
//TO DO: ADD CODE HERE BY CONVERTING ALGORITHM ON PAGE 172 OF BOOK //
/////////////////////////////////////////////////////////////////////
char[] tokens = inFix.toCharArray();
for(int i = 0; i < tokens.length; i++)
{
if(tokens[i] == ' ')
continue;
// Current token is a number, push it to stack for numbers
if (tokens[i] >= '0' && tokens[i] <= '9')
{
StringBuffer sbuf = new StringBuffer();
// There may be more than one digits in number
while (i < tokens.length && tokens[i] >= '0' && tokens[i] <= '9')
sbuf.append(tokens[i++]);
valueStack.push(Integer.parseInt(sbuf.toString()));
}
// Current token is an opening brace, push it to 'ops'
else if (tokens[i] == '(')
operatorStack.push(tokens[i]);
// Closing brace encountered, solve entire brace
else if (tokens[i] == ')')
{
while (operatorStack.peek() != '(')
{
int op1 = valueStack.pop();
int op2 = valueStack.pop();
valueStack.push(evaluateOperation(operatorStack.pop(), op2, op1));
}
operatorStack.pop();
}
// Current token is an operator.
else if (tokens[i] == '+' || tokens[i] == '-' ||
tokens[i] == '*' || tokens[i] == '/' || tokens[i] == '^')
{
// While top of 'ops' has same or greater precedence to current
// token, which is an operator. Apply operator on top of 'ops'
// to top two elements in values stack
while (!operatorStack.empty() && checkPrecedence(tokens[i], operatorStack.peek()))
{
int op1 = valueStack.pop();
int op2 = valueStack.pop();
valueStack.push(evaluateOperation(operatorStack.pop(), op2, op1));
}
// Push current token to 'ops'.
operatorStack.push(tokens[i]);
}
}
// Entire expression has been parsed at this point, apply remaining
// ops to remaining values
while (!operatorStack.empty())
{
int op1 = valueStack.pop();
int op2 = valueStack.pop();
valueStack.push(evaluateOperation(operatorStack.pop(), op2, op1));
}
// Top of 'values' contains result, return it
return valueStack.pop().toString();
}
OUTPUT
HOPE ANSWER THE QUESTION
COMMENT BELOW IF HAVING ANY DOUBT
Evaluateeg EvaluateInFix.java: import java.util.Stack; import java.util.Scanner; public class EvaluateInfix { public static void main(String[] args)...
The code below accepts and evaluates an integer expression with the following operators: +, _, *, and /. Your task is to modify it to include the % remainder operator that has the same precedence as * and /. No need to rewrite the entire program, just insert the needed statements. import java.util.Stack; public class EvaluateExpression { public static void main(String[] args) { // Check number of arguments passed if (args.length != 1) { System.out.println( "Usage:...
import java.util.Scanner; public class Client{ public static void main(String args[]){ Coin quarter = new Coin(25); Coin dime = new Coin(10); Coin nickel = new Coin(5); Scanner keyboard = new Scanner(System.in); int i = 0; int total = 0; while(true){ i++; System.out.println("Round " + i + ": "); quarter.toss(); System.out.println("Quarter is " + quarter.getSideUp()); if(quarter.getSideUp() == "HEADS") total = total + quarter.getValue(); dime.toss(); System.out.println("Dime is " + dime.getSideUp()); if(dime.getSideUp() == "HEADS") total = total +...
import java.util.Scanner; public class StudentClient { public static void main(String[] args) { Student s1 = new Student(); Student s2 = new Student("Smith", "123-45-6789", 3.2); Student s3 = new Student("Jones", "987-65-4321", 3.7); System.out.println("The name of student #1 is "); System.out.println("The social security number of student #1 is " + s1.toString()); System.out.println("Student #2 is " + s2); System.out.println("the name of student #3 is " + s3.getName()); System.out.println("The social security number...
import java.util.ArrayList; import java.util.List; import java.util.Stack; public class Main { public static void main(String[] args) { int programCounter = 0; List<String> program = new ArrayList<String>(); Stack<String> stack = new Stack<String>(); // TODO string probably not best program.add("GOTO start<<1>>"); program.add("LABEL Read"); program.add("LINE -1"); program.add("FUNCTION Read -1 -1"); program.add("READ"); program.add("RETURN "); program.add("LABEL Write"); program.add("LINE -1"); program.add("FUNCTION Write -1 -1"); program.add("FORMAL dummyFormal 0"); program.add("LOAD 0 dummyFormal"); program.add("WRITE"); program.add("RETURN "); program.add("LABEL start<<1>>"); program.add("LINE 1"); program.add("FUNCTION main 1 4"); program.add("LIT 0 i"); program.add("LIT 0 j");...
Explain this java code, please. import java.util.Scanner; public class Program11 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); final int maxSize = 128; String[] titles = new String[maxSize]; int[] lengths = new int[maxSize]; int numDVDs = 0; String op; op = menu(stdIn); System.out.println(); while (!op.equalsIgnoreCase("q")) { if (op.equalsIgnoreCase("a")) { if (numDVDs < maxSize) numDVDs = addDVD(titles, lengths, numDVDs, stdIn); } else if (op.equalsIgnoreCase("t")) searchByTitle(titles, lengths, numDVDs, stdIn); else if (op.equalsIgnoreCase("l")) searchByLength(titles, lengths, numDVDs, stdIn); System.out.println('\n');...
import java.util.Scanner; public class TriangleMaker { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Welcome to the Triangle Maker! Enter the size of the triangle."); Scanner keyboard = new Scanner(System.in); int size = keyboard.nextInt(); for (int i = 1; i <= size; i++) { for (int j = 0; j < i; j++) { System.out.print("*"); } System.out.println(); } for (int...
import java.util.Scanner; import java.util.ArrayList; public class P3A2_BRANDT_4005916 { public static void main(String[] args) { String name; String answer; int correct = 0; int incorrect = 0; Scanner phantom = new Scanner(System.in); System.out.println("Hello, What is your name?"); name = phantom.nextLine(); System.out.println("Welcome " + name + "!\n"); System.out.println("My name is Danielle Brandt. " +"This is a quiz program that...
Project 7-3 Guessing Game import java.util.Scanner; public class GuessNumberApp { public static void main(String[] args) { displayWelcomeMessage(); // create the Scanner object Scanner sc = new Scanner(System.in); String choice = "y"; while (choice.equalsIgnoreCase("y")) { // generate the random number and invite user to guess it int number = getRandomNumber(); displayPleaseGuessMessage(); // continue until the user guesses the number int guessNumber = 0; int counter = 1; while (guessNumber != number) { // get a valid int from user guessNumber...
make this program run import java.util.Scanner; public class PetDemo { public static void main (String [] args) { Pet yourPet = new Pet ("Jane Doe"); System.out.println ("My records on your pet are inaccurate."); System.out.println ("Here is what they currently say:"); yourPet.writeOutput (); Scanner keyboard = new Scanner (System.in); System.out.println ("Please enter the correct pet name:"); String correctName = keyboard.nextLine (); yourPet.setName (correctName); System.out.println ("Please enter the correct pet age:"); int correctAge = keyboard.nextInt (); yourPet.setAge (correctAge); System.out.println ("Please enter the...
Write a java code to implement the infix to postfix algorithm as described below: Algorithm convertTo Post fix ( infix) // Converts an infix expression to an equivalent postfix expression operatorStack = a new empty stack postfix = anew empty string while (infix has characters left to parse) nextCharacter =next nonblank character of infix switch (nextCharacter) { case variable: Append nextCharacter to postfix break case 'A' operatorStack.push (nextCharacter) break case '+ case '-' : case '*' : case '/' while...