Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

import java.util.Scanner; import java.util.Stack; import javafx.application.Appl

ID: 3663943 • Letter: I

Question

import java.util.Scanner;

import java.util.Stack;

import javafx.application.Application;

import javafx.event.ActionEvent;

import javafx.scene.Scene;

import javafx.scene.control.Label;

import javafx.scene.control.TextArea;

import javafx.scene.control.TextField;

import javafx.scene.layout.BorderPane;

import javafx.scene.layout.HBox;

import javafx.scene.text.Font;

import javafx.scene.text.FontPosture;

import javafx.scene.text.FontWeight;

import javafx.stage.Stage;

public class EvaluateExpression extends Application {

BorderPane bp = new BorderPane();

TextField tf = new TextField();

TextArea text = new TextArea();

@Override

public void start(Stage primaryStage) throws Exception {

// TODO Auto-generated method stub

HBox hbox = new HBox();

tf.setPrefColumnCount(40);

hbox.getChildren().addAll(new Label("Please enter arithmetic expression "), tf);

bp.setTop(hbox);

tf.setFont(Font.font("Times New Roman", FontWeight.BOLD, FontPosture.REGULAR, 20));

text.setFont(Font.font("Times New Roman", FontWeight.BOLD, FontPosture.REGULAR, 18));

bp.setCenter(text);

tf.setOnAction(this::computeExpression);

Scene scene = new Scene(bp, 700,400);

primaryStage.setScene(scene);

primaryStage.setTitle("Evaluating arithmetic expression");

primaryStage.show();

}

public static void main(String[] args) {

Application.launch(args);

}

public void computeExpression(ActionEvent e){

// test case (5*2^3+2*3%2)*4

// test case (1+2)*4-3

text.clear();

Integer result = evaluateExpression(tf.getText());

text.appendText(result.toString());

}

/** Evaluate an expression */

public int evaluateExpression(String expression) {

// Create operandStack to store operands

Stack<Integer> operandStack = new Stack<>();

// Create operatorStack to store operators

Stack<Character> operatorStack = new Stack<>();

// Insert blanks around (, ), +, -, /, and *

expression = insertBlanks(expression);

// Extract operands and operators

String[] tokens = expression.split("\s+");

// Phase 1 Scan tokens

for (String token : tokens) {

if (token.length() == 0) // Blank space

continue; // Back to the while loop to extract the next token

// Phase 1.2

else if (token.charAt(0) == '+' || token.charAt(0) == '-') {

while (!operatorStack.isEmpty()

&& (operatorStack.peek() == '+'

|| operatorStack.peek() == '-'

|| operatorStack.peek() == '*'

|| operatorStack.peek() == '/')) {

processAnOperator(operandStack, operatorStack);

}

// Push the + or - operator into the operator stack

operatorStack.push(token.charAt(0));

// Phase 1.3

} else if (token.charAt(0) == '*' || token.charAt(0) == '/') {

// Process all *, /, % in the top of the operator stack

while (!operatorStack.isEmpty()

&& (operatorStack.peek() == '*'

|| operatorStack.peek() == '/')) {

processAnOperator(operandStack, operatorStack);

}

// Push the * or / operator into the operator stack

operatorStack.push(token.charAt(0));

} else if (token.trim().charAt(0) == '(') {

operatorStack.push('('); // Push '(' to stack

// phase 1.5

} else if (token.trim().charAt(0) == ')') {

// Process all the operators in the stack until seeing '('

while (operatorStack.peek() != '(') {

processAnOperator(operandStack, operatorStack);

}

operatorStack.pop(); // Pop the '(' symbol from the stack

// phase 1.1

} else { // An operand scanned

// Push an operand to the stack

operandStack.push(new Integer(token));

}

//output

text.appendText("Operand stack: " + operandStack.toString() + " ");

text.appendText("Operator stack: " + operatorStack.toString() + " ");

}

// Phase 2 Clearing the stack

//Process all the remaining operators in the stack

while (!operatorStack.isEmpty()) {

processAnOperator(operandStack, operatorStack);

text.appendText("Operand stack: " + operandStack.toString() + " ");

text.appendText("Operator stack: " + operatorStack.toString() + " ");

}

// Return the result

return operandStack.pop();

}

/**

* Process one operator: Take an operator from operatorStack and apply it on

* the operands in the operandStack

*/

public void processAnOperator(Stack<Integer> operandStack,

Stack<Character> operatorStack) {

char op = operatorStack.pop();

int op1 = operandStack.pop();

int op2 = operandStack.pop();

if (op == '+')

operandStack.push(op2 + op1);

else if (op == '-')

operandStack.push(op2 - op1);

else if (op == '*')

operandStack.push(op2 * op1);

else if (op == '/')

operandStack.push(op2 / op1);

}

public String insertBlanks(String s) {

StringBuilder result = new StringBuilder();

for (int i = 0; i < s.length(); i++) {

if (s.charAt(i) == '(' || s.charAt(i) == ')' || s.charAt(i) == '+'

|| s.charAt(i) == '-' || s.charAt(i) == '*'

|| s.charAt(i) == '/' ){

result.append(" ");

result.append(s.charAt(i));

result.append(" ");

// result += "" + s.charAt(i) + "";

}else{

result.append(s.charAt(i));

// result += s.charAt(i);

}

}

return result.toString();

}

}

1) Complete the code above.

2) (2 pts) Write a program that reads words from your input and display all words in the inserted order.

3) (3 pts) Write a program that reads words from your input and displays all the non-duplicate words in ascending order.

4) (2 pts) Rewrite 3) using one of set data structure.

5) (2pts) Write a program that reads words from a text file and display all the non duplicate words in ascending order.

6) (3 pts) Write a program that reads a text file and displays the number of each vowel (a, e, i, o, u) in the file.

7) (3 pts) Write a program that reads a text file and count the occurrences of words in the text file and display the words and number of occurrences

Explanation / Answer

2)  all words in the inserted order.

package com.java2novice.algos;

import java.io.BufferedReader;

import java.io.DataInputStream;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.List;

import java.util.StringTokenizer;

public class MyDistinctFileWords {

    public List<String> getDistinctWordList(String fileName){

        FileInputStream fis = null;

        DataInputStream dis = null;

        BufferedReader br = null;

        List<String> wordList = new ArrayList<String>();

        try {

            fis = new FileInputStream(fileName);

            dis = new DataInputStream(fis);

            br = new BufferedReader(new InputStreamReader(dis));

            String line = null;

            while((line = br.readLine()) != null){

                StringTokenizer st = new StringTokenizer(line, " ,.;:"");

                while(st.hasMoreTokens()){

                    String tmp = st.nextToken().toLowerCase();

                    if(!wordList.contains(tmp)){

                        wordList.add(tmp);

                    }

                }

            }

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } finally{

            try{if(br != null) br.close();}catch(Exception ex){}

        }

        return wordList;

    }

     

    public static void main(String a[]){

         

        MyDistinctFileWords distFw = new MyDistinctFileWords();

        List<String> wordList = distFw.getDistinctWordList("C:/sample.txt");

        for(String str:wordList){

            System.out.println(str);

        }

    }

}

3) non-duplicate words in ascending order.

import java.util.*;

public class NonduplicateWords {

    public static void main(String[] args) {

        String text = "Testing. I have a testing text. Have a great day";

        TreeSet<String> set = new TreeSet<String>();

        String[] words = text.split("[ .,;:!?(){}]");

        for (int i = 0; i < words.length; i++) {

            String value = words[i].toLowerCase();

            if (words[i].length() > 0)

                set.add(value);

        }

        for (Object element: set)

            System.out.println(element.toString() + " ");

    }

}

5) Reads input from file

import java.util.*;

public class NonduplicateWords {

String text = "Testing. I have a testing text. Have a great day";

TreeSet<String> set = new TreeSet<String>();

        String[] words = text.split("[ .,;:!?(){}]");

        for (int i = 0; i < words.length; i++) {

            String value = words[i].toLowerCase();

            if (words[i].length() > 0)

                set.add(value);

        }

        for (Object element: set)

            System.out.println(element.toString() + " ");

    }

}

6)

7)