0

I have been trying to solve this problem since 2 days.I am not able to understand what mistake I am doing.

I am implementing a Stack class Stack1 which has the methods push,pop and peak.

I n the main method of the Stack1 class for each t testcase I am creating Stack1 stack and performing 'n'push pop and peak operations based on inputs given by user

The program is taking inputs but not providing any output

RAther it is just terminating after taking inputs

It would be great if someone would help me. Thank You

Here's my code

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Scanner;

public class Stack1 {
static final  int max=1000000;
    int top;
    int[] arr=new int[max];
    Stack1()
    {
        this.top=-1;

    }
    public void push(int val)
    {
        if(top<max-1)
        this.arr[++top]=val;
    }
    public int pop()
    {
        if(top!=-1)
          return arr[top--];

            return -110;
    }
    public int peak()
    {
        if(top!=-1)
        {
            int maxi=arr[0];
                for(int i=0;i<=top;i++)
                {
                    if(maxi<arr[i])
                        maxi=arr[i];
                }
            return maxi;
        }
        return -1;
    }
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
        int t=Integer.parseInt(br.readLine());
        Stack1[] st=new Stack1[t];

        for(int i=0;i<t;i++)
        {
             st[i]=new Stack1();
            int n=Integer.parseInt(br.readLine());
            while(n-->0)
            {
            String[] str=br.readLine().split(" ");

              if(str.length==2)
              {
                  int k=Integer.parseInt(str[1]);
                  st[i].push(k);

              }
             if(str[0]=="R")
            {
                int r=st[i].pop();
                if(r==-1)
                    bw.write("Empty\n");
                else
                    bw.write(r+"\n");
            }
            if(str[0]=="Q")
            {
                int q=st[i].peak();
                if(q==-1)
                    bw.write("Empty\n");
                else
                    bw.write(q+"\n");

            }
            }
        }
        bw.flush();

   }


}

I don't know where it is going wrong It is taking all the inputs but is not providing any output //

1 Answers1

2

str[0]=="Q" and str[0]=="R" will always return false. == is a relational operator for primitives. You need to compare objects using their implemented equals method. This is a common mistake in Java.

ricol070
  • 492
  • 2
  • 11
Malt
  • 28,965
  • 9
  • 65
  • 105