Question

In: Computer Science

Can you fix my code and remove the errors in java language. public class LinkedStack<T> implements...

Can you fix my code and remove the errors in java language.

public class LinkedStack<T> implements Stack<T> {

private Node<T> top;

private int numElements = 0;

public int size() {

return (numElements);

}

public boolean isEmpty() {

return (top == null);

}

public T top() throws StackException {

if (isEmpty())

throw new StackException("Stack is empty.");

return top.info;

}

public T pop() throws StackException {

Node<T> temp;

if (isEmpty())

throw new StackException("Stack underflow.");

temp = top;

top = top.getLink();

return temp.getInfo();

}

public void push(T item) {

Node<T> newNode = new Node();

newNode.setInfo(item);

newNode.setLink(top);

top = newNode;

}

@Override
public T peek() throws StackException {
return null;
}

@Override
public void clear() {

}

@Override
public int search(T item) {
return 0;
}

}

////////////////////////////////////////////////////

public interface Stack<T> {

public int size(); /* returns the size of the stack */ public boolean isEmpty(); /* checks if empty */

public T top() throws StackException;

public T pop() throws StackException;

public void push(T item) throws StackException;

public T peek() throws StackException;

public void clear();

public int search(T item);

}


class StackException extends RuntimeException {

public StackException(String err) {

super(err);

}

}

}

//////////////////////////////////////////////////

public class Node<T> {

public T info;

private Node<T> link;

public Node() { }

public Node (T info, Node<T> link) {

this.info = info;

this.link = link;

}

public void setInfo(T info) {

this.info = info;

}

public void setLink(Node<T> link) {

this.link = link;

}

public T getInfo() {

return info;

}

public Node<T> getLink() {

return link;

}

}

postfixExpression = empty String

operatorStack = empty stack

while (not end of infixExpression) {

symbol = next token

if (symbol is an operand)

concatenate symbol to postfixExpression

else { // symbol is an operator

while (not operatorStack.empty() &&

precedence(operatorStack.peek(),symbol) { topSymbol = operatorStack.pop();

concatenate topSymbol to postfixExpression;

} // end while

if (operatorStack.empty() || symbol != )’'/U2019' ) operatorStack.push(symbol);

else // pop the open parenthesis and discard it topSymbol = operatorStack.pop();

} // end else

} // end while

// get all remaining operators from the stack

while (not operatorStack.empty) {

topSymbol = operatorStack.pop();

concatenate topSymbol to postfixExpression

} // end while

return postfixExpression

//////////////////////////////////////////////////

import java.util.*;
class StackLinklist {
Node head=new Node(); //head pointer of linked list

public boolean isEmpty() //check whether stack empty or not
{
if(head == null)
return true;
return false;
}

public void push(char x) //add element eo stack
{
Node t=new Node();
if (t != null) {
t.op=x;
t.next=head;
head=t;
}
else{
System.out.print("Stack overflow"); //heap overflow
return;
}
}

public char topmost() // return top most caharater of stack
{
if (!isEmpty()) {
return head.op;
}
else {
System.out.println("Stack is empty");
return '\0';
}
}


public char pop() // remove the element
{
// underflow
if (head == null) {
System.out.print("\nStack Underflow");
return '\0';
}
char chp=head.op;
head = (head).next;
return chp;
}


private class Node { // class of linked list which denotes eac node
char op;
Node next;
}

}
class InfixTOPostfixConversion
{


static String infixToPostfix(String str)
{
String r ="";
StackLinklist stack = new StackLinklist();
for (int i = 0; i<str.length(); ++i)
{
char c = str.charAt(i);
if (c == '(') //if opening bracket occur,add it into stack
stack.push(c);

else if (c == ')') //case for closing bracket
{
while (!stack.isEmpty() && stack.topmost() != '(')
r+= stack.pop();

if (!stack.isEmpty() && stack.topmost() != '(')
return "invalid expression";
else
stack.pop();
}

// case of operands
else if((c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' &&c<='9'))
r+=c;

else // case of operators, operartors will be poped baed on precedence
{
while (!stack.isEmpty() && Precedence(stack.topmost()) >= Precedence(c)){
if(stack.topmost() == '(')
return "invalid expression";
else
r+= stack.pop();
}
stack.push(c);
}

}
while (!stack.isEmpty()){
if(stack.topmost() == '(')
return "invalid expression";
r+= stack.pop();
}
return r;
}


public static void main(String[] args)
{
Scanner ob=new Scanner(System.in);
while(true){
int flag=0;
System.out.println("press 1 to enter infix string, press 2 to exit");
int n=ob.nextInt();
switch(n){
case 1:
System.out.println("Enter the infix expression");
ob.nextLine();
String s=ob.nextLine();
String r=infixToPostfix(s);
if(r.equals("invalid expression"))
System.out.println(r);
else
System.out.println("Postfix Expression of given expression is "+r);
break;
case 2:
flag=1;
break;
default:
System.out.println("please enter avalid input");
}
if(flag==1)
break;
System.out.println();
System.out.println();
}

}

static int Precedence(char ch) // function for deciding operator precedence
{
int p=-1;
if(ch=='^'){
p=1000;
}
else if(ch=='*'){
p=500;
}
else if(ch=='/'){
p=500;
}
else if(ch=='+'){
p=100;
}
else if(ch=='-'){
p=100;
}
return p;
}
}

Solutions

Expert Solution

Following java program provides 2 options to user : 1 or 2.

Option 1, user is asked to enter the infix expression, as a result, postfix equivalent of expression is displayed.
Option 2, exits the program.

PFB source code for all shared files.
Corrections : There was extra code was added in the end of Node class, which was not part of any block. Hence removed it.

Code is tested , also sharing sample output below.


--------------------
LinkedStack.java
--------------------
public class LinkedStack<T> implements Stack<T> {

private Node<T> top;

private int numElements = 0;

public int size() {

return (numElements);

}

public boolean isEmpty() {

return (top == null);

}

public T top() throws StackException {

if (isEmpty())

throw new StackException("Stack is empty.");

return top.info;

}

public T pop() throws StackException {

Node<T> temp;

if (isEmpty())

throw new StackException("Stack underflow.");

temp = top;

top = top.getLink();

return temp.getInfo();

}

public void push(T item) {

Node<T> newNode = new Node();

newNode.setInfo(item);

newNode.setLink(top);

top = newNode;

}

@Override
public T peek() throws StackException {
return null;
}

@Override
public void clear() {

}

@Override
public int search(T item) {
return 0;
}

}
--------------------


--------------------
Node.java
--------------------
public class Node<T> {

public T info;

private Node<T> link;

public Node() {
}

public Node(T info, Node<T> link) {

this.info = info;

this.link = link;

}

public void setInfo(T info) {

this.info = info;

}

public void setLink(Node<T> link) {

this.link = link;

}

public T getInfo() {

return info;

}

public Node<T> getLink() {

return link;

}

}
--------------------


--------------------
Stack.java
--------------------
public interface Stack<T> {

public int size();

/* returns the size of the stack */ public boolean isEmpty(); /* checks if empty */

public T top() throws StackException;

public T pop() throws StackException;

public void push(T item) throws StackException;

public T peek() throws StackException;

public void clear();

public int search(T item);

}

class StackException extends RuntimeException {

/**
   *
   */
private static final long serialVersionUID = 1L;

public StackException(String err) {

super(err);

}

}

--------------------


--------------------
StackLinlist.java
--------------------
import java.util.*;

class StackLinklist {
Node head = new Node(); // head pointer of linked list

public boolean isEmpty() // check whether stack empty or not
{
if (head == null)
return true;
return false;
}

public void push(char x) // add element eo stack
{
Node t = new Node();
if (t != null) {
t.op = x;
t.next = head;
head = t;
} else {
System.out.print("Stack overflow"); // heap overflow
return;
}
}

public char topmost() // return top most caharater of stack
{
if (!isEmpty()) {
return head.op;
} else {
System.out.println("Stack is empty");
return '\0';
}
}

public char pop() // remove the element
{
// underflow
if (head == null) {
System.out.print("\nStack Underflow");
return '\0';
}
char chp = head.op;
head = (head).next;
return chp;
}

private class Node { // class of linked list which denotes eac node
char op;
Node next;
}

}

class InfixTOPostfixConversion {

static String infixToPostfix(String str) {
String r = "";
StackLinklist stack = new StackLinklist();
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
if (c == '(') // if opening bracket occur,add it into stack
stack.push(c);

else if (c == ')') // case for closing bracket
{
while (!stack.isEmpty() && stack.topmost() != '(')
r += stack.pop();

if (!stack.isEmpty() && stack.topmost() != '(')
return "invalid expression";
else
stack.pop();
}

// case of operands
else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
r += c;

else // case of operators, operartors will be poped baed on precedence
{
while (!stack.isEmpty() && Precedence(stack.topmost()) >= Precedence(c)) {
if (stack.topmost() == '(')
return "invalid expression";
else
r += stack.pop();
}
stack.push(c);
}

}
while (!stack.isEmpty()) {
if (stack.topmost() == '(')
return "invalid expression";
r += stack.pop();
}
return r;
}

public static void main(String[] args) {
Scanner ob = new Scanner(System.in);
while (true) {
int flag = 0;
System.out.println("press 1 to enter infix string, press 2 to exit");
int n = ob.nextInt();
switch (n) {
case 1:
System.out.println("Enter the infix expression");
ob.nextLine();
String s = ob.nextLine();
String r = infixToPostfix(s);
if (r.equals("invalid expression"))
System.out.println(r);
else
System.out.println("Postfix Expression of given expression is " + r);
break;
case 2:
flag = 1;
break;
default:
System.out.println("please enter avalid input");
}
if (flag == 1)
break;
System.out.println();
System.out.println();
}

}

static int Precedence(char ch) // function for deciding operator precedence
{
int p = -1;
if (ch == '^') {
p = 1000;
} else if (ch == '*') {
p = 500;
} else if (ch == '/') {
p = 500;
} else if (ch == '+') {
p = 100;
} else if (ch == '-') {
p = 100;
}
return p;
}
}
--------------------


--------------------
sample output
--------------------


--------------------


Let me know, if you face any issue.


Related Solutions

Can you fix my code and remove the errors? Thank you!! ^^ ////////////////////////////////////////////////////////////////////////////////////////////////////// public class StackException<T,...
Can you fix my code and remove the errors? Thank you!! ^^ ////////////////////////////////////////////////////////////////////////////////////////////////////// public class StackException<T, size> extends Throwable { private final T[] S = null ; public StackException(String s) { } public T top() throws StackException { if (isEmpty()) throw new StackException("Stack is empty."); int top = 0; return S[top]; } private boolean isEmpty() { return false; } public T pop() throws StackException { T item; if (isEmpty()) throw new StackException("Stack underflow."); int top = 0; item = S[top];...
Write a java code for LinkedStack implementation and the code is: public final class LinkedStack<T> implements...
Write a java code for LinkedStack implementation and the code is: public final class LinkedStack<T> implements StackInterface<T> {    private Node topNode; // References the first node in the chain       public LinkedStack()    {        topNode = null;    } // end default constructor       public void push(T newEntry)    { topNode = new Node(newEntry, topNode); //       Node newNode = new Node(newEntry, topNode); //       topNode = newNode;    } // end push    public...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public...
Can you fix the errors in this code? import java.util.Scanner; public class Errors6 {    public static void main(String[] args) {        System.out.println("This program will ask the user for three sets of two numbers and will calculate the average of each set.");        Scanner input = new Scanner(System.in);        int n1, n2;        System.out.print("Please enter the first number: ");        n1 = input.nextInt();        System.out.print("Please enter the second number: ");        n2 =...
I Have posted my Java code below. Fix the toString, add, and remove implementations so that...
I Have posted my Java code below. Fix the toString, add, and remove implementations so that the following test cases work. Note: I have removed all the unnecessary inherited List implementations. I have them to: throw new UnsupportedException(); For compilation, you could also add //TODO. Test (Main) List list = new SparseList<>(); list.add("0"); list.add("1"); list.add(4, "4"); will result in the following list of size 5: [0, 1, null, null, 4]. list.add(3, "Three"); will result in the following list of size...
Fix the following java code package running; public class Run {    public double distance; //in...
Fix the following java code package running; public class Run {    public double distance; //in kms    public int time; //in seconds    public Run prev;    public Run next;    //DO NOT MODIFY - Parameterized constructor    public Run(double d, int t) {        distance = Math.max(0, d);        time = Math.max(1, t);    }       //DO NOT MODIFY - Copy Constructor to create an instance copy    //NOTE: Only the data section should be...
In Java, please write a tester code. Here's my code: public class Bicycle {     public...
In Java, please write a tester code. Here's my code: public class Bicycle {     public int cadence; public int gear;   public int speed;     public Bicycle(int startCadence, int startSpeed, int startGear) {         gear = startGear;   cadence = startCadence; speed = startSpeed;     }     public void setCadence(int newValue) {         cadence = newValue;     }     public void setGear(int newValue) {         gear = newValue;     }     public void applyBrake(int decrement) {         speed -= decrement;    ...
Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner;...
Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner; public class Booolean0p {        public class BooleanOp {            public static void main(String[] args) {                int a = 0, b = 0 , c = 0;                Scanner kbd = new Scanner(System.in);                System.out.print("Input the first number: ");                a = kbd.nextInt();                System.out.print("Input...
How do I fix my code? public class Fraction {    private int numerator, denominator, numberOfFraction;    public...
How do I fix my code? public class Fraction {    private int numerator, denominator, numberOfFraction;    public Fraction () {    numerator = 0;    denominator = 1;    numberOfFraction++; }    public Fraction (int n, int d) {    numerator = n;    denominator = d;    numberOfFraction++; } private int gcd (int num1, int num2) {    if (num1 == 0)    return num2;    return gcd (num2 % num1, num1); }    public Fraction add (Fraction third) {    int n = numerator * third.denominator + third.numerator * denominator;    int...
Fix the following codes in JAVA so they can work : public class GeometricObject { private...
Fix the following codes in JAVA so they can work : public class GeometricObject { private String color = "white"; private boolean filled; private java.util.Date dateCreated; public GeometricObject1() { dateCreated = new java.util.Date(); } public GeometricObject1(String Color, boolean filled) { dateCreated = new java.util.Date(); this.color = color; this.filled = filled; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public boolean isFilled() { return filled; } public void setFilled(boolean filled) { this.filled...
Language: Java Topic: Deques Using the following variables/class: public class ArrayDeque<T> { /** * The initial...
Language: Java Topic: Deques Using the following variables/class: public class ArrayDeque<T> { /** * The initial capacity of the ArrayDeque. * * DO NOT MODIFY THIS VARIABLE. */ public static final int INITIAL_CAPACITY = 11; // Do not add new instance variables or modify existing ones. private T[] backingArray; private int front; private int size; Q1: write a method called "public void addLast(T data)" which adds an element to the back of a Deque. If sufficient space is not available...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT