Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / April 2007

Tip: Looking for answers? Try searching our database.

Help with comparing objects

Thread view: 
Taria - 04 Apr 2007 00:00 GMT
I have been working on the proverbial postfix program for awhile and
found this error.  I am having trouble comparing objects with a
value.  I tried to put the value into an object structure but it still
doesn't work.    It pops beyond where I expect then has an out of
bounds error.

This is a simpler version of my program, please don't laugh.  I have
cut and pasted out the problem area.  The "while" condition never
returns true when it should. hrmph.  Also, our professor required we
write our own Stack class instead of using java's stack class..so I
included that as well.   Any hints...is appreciated.

   public class MyProg{

      public static void main(String[] args) {

        String infixInput = "a-(b+c*d)/e";
        Expression LParenthesis = new Expression("(");
        Stack operatorStack = new Stack();
        operatorStack.push("-");
        operatorStack.push("(");
        operatorStack.push("-");
        operatorStack.push(")");
        operatorStack.push("*");
        while (operatorStack.top() != LParenthesis){
             System.out.println ("Popping top off: "+operatorStack.top());
             operatorStack.pop();
         }
     }
  }
  /**Class Expression storage*/
   class Expression{
     private String equation = "";
      public Expression()
{
     }
     public Expression(String newExpression)
{
        this.equation = newExpression;
     }
     public String toString(){
        String string = equation;
        return string;
     }
  }

public class Stack {
 private static final int MAX_SIZE = 10;
 private int count = 0;
 private Object[] array;

 /*
  * Constructor that defines the layout of the stack
  */
 public Stack (){
   // instantiation of the object "stack"
   this.array = new Object[MAX_SIZE];
   this.count = 0;
 }

 public Object top(){
   return this.array[count-1];
 }

 public boolean isEmpty(){
   if (this.count == 0){
     return true;
   }
   return false;
 }

 public int size(){
   return this.count;
 }

 public boolean push(Object newItem){
   if (count == MAX_SIZE){
     return false;
   }
   this.array[count++] = newItem;
   return true;
 }

 public Object pop(){
   if (count <=0) {
     return null;
   }
   return this.array[--count];
 }

 public void popAll(){
   for (int i=0;i==count;i++){
     array[i] = null;
   }
   count = 0;
 }
}
Daniel Pitts - 04 Apr 2007 00:07 GMT
> I have been working on the proverbial postfix program for awhile and
> found this error.  I am having trouble comparing objects with a
[quoted text clipped - 8 lines]
> included that as well.   Any hints...is appreciated.
>          while (operatorStack.top() != LParenthesis){
Hint #1:
don't use !=, use !operatorStack.top().equals(LParenthesis)
Hint #2:
You are pushing Strings, and comparing to Expressions...
Try using:
while (!operatorStack.top().equals("("))
Taria - 04 Apr 2007 03:14 GMT
> On Apr 3, 4:00 pm, "Taria" <mche...@hotmail.com> wrote:> I have been working on the proverbial postfix program for awhile and
> > found this error.  I am having trouble comparing objects with a
[quoted text clipped - 15 lines]
> Try using:
>  while (!operatorStack.top().equals("("))

You know I tried the above on my mini program and it works like a
charm.  I inserted the tweaked corrected code into my main program and
it still skips it :(.  Thank you very much for your help.  If I can
get it to work in my mini program, I should soon be able to make the
bigger one cooperate too.

The main program pushes characters into a stack as follows:

for (int i = 0;i < size; i++){
           char ch = infixInput.charAt(i);
           if (ch == '+' || ch == '-' || ch == '/' || ch == '*' || ch
== '('){
              operatorStack.push(ch);
           }
...
}

So, my mini program is different in that way, does it make that much
of a different whether it's a character or string you're pushing onto
it?  I'm getting confused!   I'll play around with it a bit more

Thanks again for your help!
Taria - 04 Apr 2007 03:18 GMT
> > On Apr 3, 4:00 pm, "Taria" <mche...@hotmail.com> wrote:> I have been working on the proverbial postfix program for awhile and
> > > found this error.  I am having trouble comparing objects with a
[quoted text clipped - 41 lines]
>
> - Show quoted text -

Never mind me!  I changed it to comparing it to a character by using
single quotes and the main program works now!!  woohoo.  /does a
little dance.  Thank you so very much, this has been a very
enlightening lesson on the characteristics of java!  :)
Lew - 04 Apr 2007 03:28 GMT
>>  char ch = infixInput.charAt(i);
>>  if (ch == '+' || ch == '-' || ch == '/' || ch == '*' || ch

1.
  if ( "+-/*(".indexOf( ch ) >= 0 )

2.
  switch ( ch )
  {
    case '+': // no break
    case '-': // no break
    case '/': // no break
    case '*': // no break
    case '(':
        ... ;
        break;
  }

Signature

Lew

Lew - 04 Apr 2007 03:26 GMT
>  char ch = infixInput.charAt(i);
>  if (ch == '+' || ch == '-' || ch == '/' || ch == '*' || ch == '('){

---
  if ( "+-/*(".indexOf( ch ) > 0 )
---
  switch ( ch )
  {
    case '+': // no break
    case '-': // no break
    case '/': // no break
    case '*': // no break
    case '(':
        ... ;
        break;
  }
---

Signature

Lew

Hendrik Maryns - 04 Apr 2007 09:09 GMT
Taria schreef:
>> On Apr 3, 4:00 pm, "Taria" <mche...@hotmail.com> wrote:> I have been working on the proverbial postfix program for awhile and
>>> found this error.  I am having trouble comparing objects with a
[quoted text clipped - 34 lines]
> of a different whether it's a character or string you're pushing onto
> it?  I'm getting confused!   I'll play around with it a bit more

Yes, it makes a difference.  Strings are objects, so they have reference
semantics.  The confusing thing here is that the JVM tries everything to
not let that be a problem, by caching strings.  However, it is still
always a good idea to do myString.equals(someString), instead of using
!=, since ‘you never know’[*].  chars on the other hand are not objects,
that is you *have to* compare them using !=.  But since you push chars
in a stack, autoboxing pops in too.  That means the Stack stores
Character instances, no chars.  Those are objects again, you can compare
them with equals, and probably should.

Another problem is that you use some self-defined Expression class to
compare with.  Then it all depends on how the involved classes define
equals().  Since you invoke equals on the String, it will most
definitely return false, since String is implemented that way.

My hints: look up autoboxing, reference vs. value semantics and think
about why you need the ‘Expression’ class, and whether you wouldn’t use
a Stack<Expression>.

HTH, H.

[*] i.e. there are cases where two strings with the same content are not
the same.  It is well-defined when this happens, but confusing to
beginners, so I’ll leave it out here.

- --
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.