First, I want to say that I am Java beginner and I do not have a lot of experience. This is my 2nd program.

My objective is to write a program using stacks to see if a line inside of a file such as test.txt has matching scope symbols such as "{[]}". If if it doesn't have matching scope symbols such as "[{]]", then I want to print that the symbols does not match.

Right now, I am trying to read into a file and then push a character inside of the file onto the stack. However, I do not know the keywords to do this successfully. I created my own Stack class which is presented below. Any help is appreciated.


my test.txt looks like {{}} right now.

import java.io.* ;

public class Stackmain {

public Stackmain() {
}
public static void main(String[] args) throws IOException {
Stack s = new Stack(10); // 10 chars
char ch;

FileInputStream fstream = new FileInputStream("test.txt");

DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;

while ((ch = (char)System.in.read()) != '\n')
if (!s.full()) s.push(ch);

} 

}

Stack Class

public class Stack {
   private int maxStack;
   private int emptyStack;
   private int top;
   private char[] items;




   public Stack(int size) {
      maxStack= size;
      emptyStack = -1;
      top = emptyStack;
      items = new char[maxStack];
   }

   

   public void push(char c) {
      items[++top] = c;
   }

   public char pop() {
      return items[top--];
   }

   public boolean full()  {
      return top + 1 == maxStack;
   }

   public boolean empty()  {
      return top == emptyStack;
   }
}

You know Java has a premade Stack class already, right? If your teacher is forcing you to make your own, that makes sense (you'll learn a lot more), but otherwise, you might want to use the existing one. Anyway, where you said

System.in.read()

you should be calling one of BufferedReader's methods to read in from the file. Something like

while ((ch = (char)br.read()) != '\n')

Also, you might want to change your code so that instead of quitting when it sees a newline, it quits when it reaches the end of the file.

I tried to test it and see if I was able to print out the stack, but it shows a blank output. Did I do something incorrect?

import java.io.* ;

public class Stackmain {

    public Stackmain() {
    }
      public static void main(String[] args) throws IOException {
    Stack s = new Stack(10); // 10 chars
    char ch;
    
    FileInputStream fstream = new FileInputStream("test.txt");

    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
  
    while ((ch = (char)br.read()) != '\n')
       if (!s.full()) s.push(ch);
       while (!s.empty())
         System.out.print(s.pop());
        System.out.println();

      } 
    
}

do i need to do s.pop() inside of the while loop and then print outside of it?

edit:

Like I told you in my previous advice, you should exit your while loop at the end of the file, not at a newline. Had you listened to that advice, your program would be working right now. (Hint: there is probably no newline in your file, thus, your while loop never exits).

Btw, your pop is perfectly fine.

Edited 6 Years Ago by BestJewSinceJC: n/a

do i need to do s.pop() inside of the while loop and then print outside of it?

It appears to work. Prints out the first 10 characters of the file test.txt

I did have to change the stack class by removing the public declaration.

Here is the contents on my test.txt file:

this is a test data file that contains important stuff.

EDIT: it prints the first 10 characters of the first line backwards, which is what I assume you are trying to do.

Edited 3 Years Ago by Nick Evan: Fixed formatting

^ What? I already told him why his file wasn't printing. Your reply makes no sense. Did you read the previous replies to this thread?

^ What? I already told him why his file wasn't printing. Your reply makes no sense. Did you read the previous replies to this thread?

...Like I told you in my previous advice, you should exit your while loop at the end of the file, not at a newline. Had you listened to that advice, your program would be working right now...

I see no useful information in your post, only a lame attempt at a mini lecture. It must be very important for you to get that "solved" gold star, right?

My post, was to show that there is indeed output happening with his code with only a single modification. You of all people, should have been smart enough to pick up on that.

So, I was addressing his concern about no output and usage of his s.pop. My apologies for not being as smart as you think you are.

Unfortunately, I am still unable to get the program to run. I also removed the public declaration from the stack class. I also don't know how to change the '\n' to the end of the file. I do not know much terminology in Java.

Unfortunately, I am still unable to get the program to run. I also removed the public declaration from the stack class. I also don't know how to change the '\n' to the end of the file. I do not know much terminology in Java.

in your source, change:

while ((ch = (char)br.read()) != '\n')

to

while ((ch = (char)br.read()) != (char)-1 )

Here is the program with the changes

import java.io.* ;
   
    class Stack {
      private int maxStack;
      private int emptyStack;
      private int top;
      private char[] items;
   
       public Stack(int size) {
         maxStack= size;
         emptyStack = -1;
         top = emptyStack;
         items = new char[maxStack];
      }
   
       public void push(char c) {
         items[++top] = c;
      }
   
       public char pop() {
         return items[top--];
      }
   
       public boolean full()  {
         return top + 1 == maxStack;
      }
   
       public boolean empty()  {
         return top == emptyStack;
      }
   }
    public class Stackmain {
   
       public Stackmain() {
      }
       public static void main(String[] args) throws IOException {
         Stack s = new Stack(10); // 10 chars
         char ch;
      
         FileInputStream fstream = new FileInputStream("test.txt");
      
         DataInputStream in = new DataInputStream(fstream);
         BufferedReader br = new BufferedReader(new InputStreamReader(in));
         String strLine;
      
         while ((ch = (char)br.read()) != (char)-1 )
            if (!s.full()) s.push(ch);
         while (!s.empty())
            System.out.print(s.pop());
         System.out.println();
      
      } 
    
   }

The program works fine...

I see no useful information in your post, only a lame attempt at a mini lecture. It must be very important for you to get that "solved" gold star, right?

My post, was to show that there is indeed output happening with his code with only a single modification. You of all people, should have been smart enough to pick up on that.

Do you read before you post? I told the OP everything he needed to know to solve his problem in post #2 and my other post in this thread. Anyone reading this thread (other than you, apparently) can attest to that. Your response to my post is overboard and childish. And you added nothing to this thread other than insults. I'll leave it at that.

Edited 6 Years Ago by BestJewSinceJC: n/a

...Your response to my post is overboard and childish...

As was your first and second responses to me cupcake :)

.And you added nothing to this thread other than insults. I'll leave it at that.

True, I did forget to include the code. Good catch on that one. I'm sure all of your friend is impressed!

Edited 6 Years Ago by PatrickSharp: n/a

Comments
useless nuisance.

The point of the forum is to help people learn. Giving them code can sometimes add to that. Giving them suggestions and guidance and letting them research and find the answers on their own is usually more helpful. Besides, my original post towards you was not complaining about you giving the OP code, it was in response to a post you made that was basically a freepost.

That is fine that you are trying to help me. Getting a stack to print was not my objective. I was just trying to see if I got my stack to work correctly. I'm not looking for anyone to give me code for me to my work. I don't learn that way. I just wanted to be pushed to the right direction. About your statement about searching, I was searched on the Internet and looked at 3 of my books on Java Programming...None have answered my question on how to read in from a file and push the items onto the stack successfully. If you guys don't mind, please stop arguing.

The point of the forum is to help people learn. Giving them code can sometimes add to that. Giving them suggestions and guidance and letting them research and find the answers on their own is usually more helpful. Besides, my original post towards you was not complaining about you giving the OP code, it was in response to a post you made that was basically a freepost.

I created a thread before but I felt it was getting to long, and I have a new problem!

First I want to say that I am a Java beginner and this is my 2nd program.

I created a program that will do a symbol balance test, but I need someone to help me print the results to the screen because I am getting a blank output whenever I try to find a way to do it. I am also reading into a file. Any help is appreciated please.

test.txt looks like {{}}

For ex,

{ { } } = the symbols are equally balanced
{ [ { } = the symbols are not equally balanced

I need someone to help me find a way to print the results like

{{}} are equally balanced
or
{[}} are not equally balanced


I tried using this and placing it near the bottom of the program in between the last brackets

while (!s.empty())
{
System.out.println(s.pop());

if (failed == true)
{
System.out.println(" symbols do not match");
}
else
{
System.out.println(" The symbols match");
}

Main program:

import java.io.* ;

public class Stackmain 
{

    public Stackmain() 
    {
    	
    	
    	
    }
    public static boolean main(String expression) throws IOException 
    {
    
    final char LEFT_PARENT = '(';
    final char RIGHT_PARENT = ')';
    final char LEFT_CURLY = '{';
    final char RIGHT_CURLY = '}';
    final char LEFT_SQUARE = '[';
    final char RIGHT_SQUARE = ']';
    
    Stack s = new Stack(100);
    char ch;
    int i = 0;
    boolean failed = false;
    
    FileInputStream fstream = new FileInputStream("test.txt");

    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
  
    while ((ch = (char)br.read()) != (char)-1 )
       if (!s.full()) 
       {
         for (i=0; !failed && (i < expression.length( )); i++)
          {
       	     switch (expression.charAt(i))
       	     {
       		  case LEFT_PARENT:
       		  case LEFT_CURLY:
       		  case LEFT_SQUARE:
       		       s.push(expression.charAt(i));
       		       break;
       		  case RIGHT_PARENT:
       		 if (s.empty() || (s.pop() != LEFT_PARENT))
       			   failed = true;
       			   break;
       	  	  case RIGHT_CURLY:
       		 if (s.empty() || (s.pop() != LEFT_CURLY))
       			   failed = true;
       			   break;
       		  case RIGHT_SQUARE:
       		 if (s.empty() || (s.pop() != LEFT_SQUARE))
       			   failed = true;
       			   break;     			 	
         	} 	
          }
       	}
       	   return (s.empty() && !failed);
     }             
}

Stack class:

class Stack {
   private int maxStack;
   private int emptyStack;
   private int top;
   private char[] items;




   public Stack(int size) {
      maxStack= size;
      emptyStack = -1;
      top = emptyStack;
      items = new char[maxStack];
   }

   

   public void push(char c) {
      items[++top] = c;
   }

   public char pop() {
      return items[top--];
   }

   public boolean full()  {
      return top + 1 == maxStack;
   }

   public boolean empty()  {
      return top == emptyStack;
   }
}

use this :
u have also not saved the text in the expression string
and before before printing plz insert the string in the stack once again using your push method as u have pop some elements;
and use this to print as u want

while (!s.empty())//this will get all the characters 
{
System.out.println(s.pop());
 }//u missed this bracket
if (failed == true)
{
System.out.println(" symbols do not match");
}
else
{
System.out.println(" The symbols match");
}

Edited 6 Years Ago by __avd: Added [code] tags. For easy readability, always wrap programming code within posts in [code] (code blocks).

do I push back into the stack inside of the while loop and then the results will print to the screen? Also, where is a good location to place that code? Should it be before or after the return statement in my code?

use this :
u have also not saved the text in the expression string
and before before printing plz insert the string in the stack once again using your push method as u have pop some elements;
and use this to print as u want

while (!s.empty())//this will get all the characters 
{
System.out.println(s.pop());
 }//u missed this bracket
if (failed == true)
{
System.out.println(" symbols do not match");
}
else
{
System.out.println(" The symbols match");
}

Edited 6 Years Ago by NinjaLink: n/a

I am still trying to print out the results. This my latest modification to my program. I am trying to print the results at towards the bottom of the program. Please help! I am still receiving a blank screen. =/


Also printing to say something like "{{}} expression does match", but it seems more difficult to do.

import java.io.* ;

public class Stackmain 
{

   // public Stackmain() 
   // {
    	
    	
   // }
    public static boolean main(String expression) throws IOException 
    {
    
    final char LEFT_PARENT = '(';
    final char RIGHT_PARENT = ')';
    final char LEFT_CURLY = '{';
    final char RIGHT_CURLY = '}';
    final char LEFT_SQUARE = '[';
    final char RIGHT_SQUARE = ']';
    
    Stack s = new Stack(100);
    char ch;
    int i = 0;
    boolean failed = false;
    
    FileInputStream fstream = new FileInputStream("test.txt");

    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
 
  
  
    while ((ch = (char)br.read()) != (char)-1 )
    {
       if (!s.full()) 
       {

         for (i=0; !failed && (i < expression.length( )); i++)
          {
       	     switch (expression.charAt(i))
       	     {
       		  case LEFT_PARENT:
       		  case LEFT_CURLY:
       		  case LEFT_SQUARE:
       		       s.push(expression.charAt(i));
       		       break;
       		  case RIGHT_PARENT:
       		 if (s.empty() || (s.pop() != LEFT_PARENT))
       			   failed = true;
       			   break;
       	  	  case RIGHT_CURLY:
       		 if (s.empty() || (s.pop() != LEFT_CURLY))
       			   failed = true;
       			   break;
       		  case RIGHT_SQUARE:
       		 if (s.empty() || (s.pop() != LEFT_SQUARE))
       			   failed = true;
       			   break;    
       			   
       			   			 	
         	} 	

          }
     }
         
}


if (failed == true)
{
	System.out.println("Expression does not match");
}
if (failed == false)
{
	System.out.println("Expression does match");
}

return (s.empty() && !failed);
}
}

Edited 6 Years Ago by NinjaLink: n/a

Apologies for arguing in your thread. It wasn't my intention to screw up your thread. Anyway, you marked this thread solved but also asked a question - are you still having trouble or not?

You should be following an algorithm similar to the one described at this webpage, but it doesn't look like you are. It looks like you're going through your String and comparing it to what is on the Stack. . which in theory would work, but you might want to consider an alternative approach: (read the algorithm described in this link)

http://www.ccs.neu.edu/home/sbratus/com1101/lab4.html

For example, lets say you have only {, }, (, and ) in your text files.

Given the (valid) input: { ( { ( ) } ) }
-Push the first open bracket onto the stack
-Now Push the first open paren onto the stack
-Push the second open bracket onto the stack
-Push the second open paren onto the stack
-Now that you see the first ), look at the stack, and attempt to pop the corresponding symbol (which is an open paren) off the stack. Success! (There was an open paren on the stack)
-Now that you see the first }, look at the stack, and attempt to pop the corresponding symbol (which is an open bracket) off the stack. Success!

etc... I hope you get the idea.

This question has already been answered. Start a new discussion instead.