Question

In: Computer Science

This question need to be solved using java coading :- I. Input All input data are...

This question need to be solved using java coading :-

I. Input

   All input data are from a file "in.dat". The file contains a
sequence of infix form expressions, one per line. The character '$' 
is an end mark. For example, the following file has four infix form 
expressions:

   1 + 2 * 3 ^ ! ( 4 == 5 ) $
   3 * ( 6 - 4 * 5 + 1) + 2 ^ 2 ^ 3 $
   77 > ( 2 - 1 ) + 80 / 4 $
   ! ( 2 + 3 * 4 >= 10 % 6 ) && 20 != 30 || 45 / 5 == 3 * 3 $

Each expression is a sequence of tokens (i.e., constant integers,
operators, and end mark) separated by spaces. There is no variable.


II. Output

   Output data and related information are sent to the screen.
Your program should do the following for each expression:

   (1) printing the expression before it is manipulated;
   (2) showing the converted postfix form expression;
   (3) showing the expression tree;
   (4) printing the fully parenthesized infix form expression;
   (5) reporting the value of the expression.


III. Operators

   The following operators are considered. They are listed in the
decreasing order of precedence.

   Token            Operator            Associativity

    !               logical not         right-to-left
    ^               exponentiation      right-to-left
    *  /  %         multiplicative      left-to-right
    +  -            additive            left-to-right
    <  <=  >  >=    relational          left-to-right
    ==  !=          equality            left-to-right
    &&              logical and         left-to-right
    ||              logical or          left-to-right


IV. Other Requirements

   Since a large amount of information are to be displayed on the
screen, it is mandatory for your program to provide users a prompting
message such as

          Press <Enter> to continue ...

after each expression is processed, so that users have the chance to
check the output of your program carefully.


V. Algorithm: Infix_to_postfix conversion

  Input:  An infix form expression E = t1 t2 t3 ... $,
          which is a sequence of tokens.
  Output: The postfix form expression of E.

  Algorithm: 
  {
    do {
      get the next token t;
      case (t) {
         operand: place t onto the output;
                  break;
        operator: while (stack s is not empty
                    && stacktop(s) is not a left parenthesis)
                    && precedence(stacktop(s)) >= precedence(t)
                       // assuming left-to-right associativity, 
                       // not for the exponentiation operator ^, 
                       // which has right-to-left associativity 
                  {
                        pop(x,s);
                        place x onto the output;
                  }
                  push(t,s);
                  break;
               (: push(t,s);
                  break;
               ): while (stacktop(s) is not a left parenthesis) {
                      pop(x,s);
                      place x onto the output;
                  }
                  pop(x,s);
                  break;
        end mark: while (stack s is not empty) {
                      pop(x,s);
                      place x onto the output;
                  }
                  place the end mark onto the output;
                  break;
      }
    } while (t is not the end mark);
  }

This below is "in.dat file"

12 * 23 <= ( ( ( 3456 ) ) +    ( 6789 ) ) $ 1
4 ^ 3 - ( 2 + 4 * 15 ) - ( 90 / 3 != 30 ) $ 2
! ( 222 < 111 ) + 2 * 3 ^ ( 29 - 3 * 9 ) > 18 && 1234 == 1234 $ 1
( 2 * ( 62 % 5 ) ) ^ ( ( 4 - 2 ) ) - 2 ^ 2 ^ 2 $ 0
( ( 9 / ( 5 - 2 ) + 2 ) * ( 2 ^ 2 * 2 ) - 79 ) || ! ( 65432 > 54321 ) $ 1
( ( 9999 >= 8888 ) + 2 ) * ( 4 / ( 999 - 997 ) ) - 2 ^ ( 5 - 3 ) $ 2

Solutions

Expert Solution

   







  
               
 

class Node {

char value;
Node left, right;

Node(char item) {
value = item;
left = right = null;
}
}

public class Main
{
   public static void main(String[] args) {
       System.out.println("Hello World");
       try {
//the file to be opened for reading
FileInputStream fis=new FileInputStream("Demo.txt");   
Scanner sc=new Scanner(fis); //file to be scanned
//returns true if there is another line to read
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
promptEnterKey();
postfix_convert(sc.nextLine());
promptEnterKey();
expression_tree(sc.nextLine());
promptEnterKey();
evaluate_exp(sc.nextLine());
}
sc.close(); //closes the scanner
}
catch(IOException e){
e.printStackTrace();
}

   }
   public void promptEnterKey(){
System.out.println("Press \"ENTER\" to continue...");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
}
   public void postfix_convert(String exp){

char sym; //to extract each character of the expression.
Stack<Character> st=new Stack<>(); //stack
HashMap<Character,Integer> priority=new HashMap<>(); //store the priority of the operators
priority.put('^',3); //priority of the '^' operator is set 3.
//priority of '*' and '/' are same and are set to 2.
priority.put('*',2);
priority.put('/',2);
//priority of '+' and '-' are same and are set to 1.
priority.put('+',1);
priority.put('-',1);
for(int i=0;i<exp.length();i++){
sym=exp.charAt(i);
if(sym=='(')
st.push(sym);
else{
if(Character.isLetterOrDigit(sym))
System.out.print(sym);
else{
if(sym==')'){
while(st.peek()!='(')
System.out.print(st.pop());
st.pop();
}
else{
while(st.size()>0 && st.peek()!='(' && priority.get(sym)<=priority.get(st.peek()))
System.out.print(st.pop());
st.push(sym);
}
}
}
}
//printing the remaining elements in the Stack
while (st.size()>0)
System.out.print(st.pop());
}
public void expression_tree(String exp){
char[] charArray = exp.toCharArray();
Node root = constructTree(charArray);
inorder(root);

}
Node constructTree(char postfix[]) {
Stack<Node> st = new Stack<Node>();
Node t, t1, t2;

// Traverse through every character of input expression
for (int i = 0; i < postfix.length; i++) {

// If operand, simply push into stack
if (!isOperator(postfix[i])) {
t = new Node(postfix[i]);
st.push(t);
}
else{ // operator
  
t = new Node(postfix[i]);

// Pop two top nodes
// Store top
t1 = st.pop(); // Remove top
t2 = st.pop();

// make them children
t.right = t1;
t.left = t2;

// System.out.println(t1 + "" + t2);
// Add this subexpression to stack
st.push(t);
}
}

// only element will be root of expression tree
t = st.peek();
st.pop();

return t;
}
boolean isOperator(char c) {
if (c == '+' || c == '-'|| c == '*' || c == '/'|| c == '^') {
return true;
}
return false;
}

// Utility function to do inorder traversal
void inorder(Node t) {
if (t != null) {
inorder(t.left);
System.out.print(t.value + " ");
inorder(t.right);
}
}
void evaluate_exp(String exp){
char[] tokens = expression.toCharArray();
  
// Stack for numbers: 'values'
Stack<Integer> values = new Stack<Integer>();
  
// Stack for Operators: 'ops'
Stack<Character> ops = new Stack<Character>();
  
for (int i = 0; i < tokens.length; i++)
{
// Current token is a whitespace, skip it
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++]);
values.push(Integer.parseInt(sbuf.toString()));
}
  
// Current token is an opening brace, push it to 'ops'
else if (tokens[i] == '(')
ops.push(tokens[i]);
  
// Closing brace encountered, solve entire brace
else if (tokens[i] == ')')
{
while (ops.peek() != '(')
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
ops.pop();
}
  
// Current token is an operator.
else if (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 (!ops.empty() && hasPrecedence(tokens[i], ops.peek()))
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
  
// Push current token to 'ops'.
ops.push(tokens[i]);
}
}
  
// Entire expression has been parsed at this point, apply remaining ops to remaining values
while (!ops.empty())
values.push(applyOp(ops.pop(), values.pop(), values.pop()));
  
// Top of 'values' contains result, return it
return values.pop();
}
public static boolean hasPrecedence(char op1, char op2)
{
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}
  
// A utility method to apply an operator 'op' on operands 'a'
// and 'b'. Return the result.
public static int applyOp(char op, int b, int a)
{
switch (op)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new
UnsupportedOperationException("Cannot divide by zero");
return a / b;
}
return 0;
}
}

Likes: 0

Dislikes: 0


Related Solutions

This question need to be solved using java coading :- I. Input All input data are...
This question need to be solved using java coading :- I. Input All input data are from a file "in.dat". The file contains a sequence of infix form expressions, one per line. The character '$' is an end mark. For example, the following file has four infix form expressions: 1 + 2 * 3 ^ ! ( 4 == 5 ) $ 3 * ( 6 - 4 * 5 + 1) + 2 ^ 2 ^ 3 $ 77...
**write a java program infix to postfix**showing the expression tree*** I. Input All input data are...
**write a java program infix to postfix**showing the expression tree*** I. Input All input data are from a file "in.dat". The file contains a sequence of infix form expressions, one per line. The character '$' is an end mark. For example, the following file has four infix form expressions: 1 + 2 * 3 ^ ! ( 4 == 5 ) $ 3 * ( 6 - 4 * 5 + 1) + 2 ^ 2 ^ 3 $ 77...
JAVA JAVA JAVA . I need to convert a string input to int array, for example...
JAVA JAVA JAVA . I need to convert a string input to int array, for example if user enters 12 / 27 / 2020 , I want to store each value in a separate array and add them afterwards.
I need to draw a cylinder in java with user input, and I can't seem to...
I need to draw a cylinder in java with user input, and I can't seem to get my lines to line up with my ovals correctly from the users input... I know I will have to either add or subtract part of the radius or height but I'm just not getting it right, here is how I'm looking to do it.            g.drawOval(80, 110, radius, height);            g.drawLine(?, ?, ?, ?); g.drawLine(?, ?, ?, ?);   ...
Could someone please answer this question? I need it to be solved in 3 hours. Thank...
Could someone please answer this question? I need it to be solved in 3 hours. Thank you so much for your help! I am really grateful! FUN Corp. is planning to add a new doll “Lisa” to their production line. Instead of purchasing a third-party research report, the marketing department of FUN Corp. conducted their own analysis which saved at least $20,000 for the firm. The assumptions about the expected revenues, expenses and capital investments are presented as the followings....
Java Programming I need an application that collects the user input numbers into an array and...
Java Programming I need an application that collects the user input numbers into an array and after that calls a method that sums all the elements of this array. and display the array elements and the total to the user. The user decides when to stop inputting the numbers. Thanks for your help!
In Java, I need a program that will ask a user to input how many tests...
In Java, I need a program that will ask a user to input how many tests they want the average of. For example, It needs to ask the user how many tests would you like the average of? When the user enters the amount of tests they want the average score of, the program needs to give them that many test scores to input. Then with the average, determine what their grade is, if 90-100=A if 80-90 = B etc....
(JAVA) I have posted the same question 2 days ago, but it still has not solved...
(JAVA) I have posted the same question 2 days ago, but it still has not solved yet. I have "cannot be resolved or is not a field" error on node.right; & node.left; under BuildExpressTree.java //Main.java import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.util.*; public class Main extends JFrame{    private GridLayout glm = new GridLayout(3, 1, 5, 20);    private JPanel jp1 = new JPanel();    private JPanel jp2 = new JPanel();    private JPanel jp3 = new...
All the question should be solved using IF statement Q1) List the Full Name, the city,...
All the question should be solved using IF statement Q1) List the Full Name, the city, and the state of all members, and order them by their first name in descending order (Z-A) if they are from 'KY' or by their last name in ascending order (A-Z) when they are from 'TN' state. Q2) List the total number of movies for each genre (FAMILY, ACTION, DRAMA, COMEDY). - Comment the following two lines if creating database in Mimir or Bluenose...
Using Java. The following is a constructor I need to implement but I am not sure...
Using Java. The following is a constructor I need to implement but I am not sure how. It also must pass the Junit test. Please give reasoning while answering. public class LZWDictionary { // FIELDS // map (for ease of checking existence of entries) // list (ease of recall of an entry) LinkedHashMap<String, Integer> map; List<String> list; /** * Initializes the LZWDictionary to have an initial set of entries taken from * the set of unique characters in a provided...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT