• Post Reply Bookmark Topic Watch Topic
  • New Topic

Truth table for logical operators  RSS feed

 
Ez Burdett
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, I give up. I've created (with help) a truth table for logical operators. Now I'm supposed to alter the code so the table prints 1's and 0's instead of true or false. Here's a bit of the original code - just the header and the first line of the table.


System.out.println("p\tq\tAND\tOR\tXOR\tNOT");
System.out.println();

boolean p, q;

p = true; q = true;
System.out.print( p + "\t" + q + "\t" );
System.out.print( ( p & q) + "\t" + ( p | q) + "\t");
System.out.println(( p ^ q ) + "\t" + ( !p) );

All of my ideas involve using an if-then statement, but that would be all kinds of inefficient and unwieldy, I think. Besides, the book I'm using hasn't really gotten into those yet, so I'm guessing there is a better way to do it.

Help?
 
Paul Clapham
Sheriff
Posts: 22829
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That seems like the ideal place to use a method which converts true to 0 and false to 1, or whatever you want it to do.
 
Ez Burdett
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That does sound like a good solution. Wish I had thought of it. But I'm not sure if that's what I'm looking for either.
 
Paul Clapham
Sheriff
Posts: 22829
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If your original post meant what I think it meant, then yes, that is what you are looking for. If you want to do the same thing in a lot of places, put that code into a method and call the method from all those places.

So instead of



you'd have



Or you could use the ternary operator if you're not allowed to write methods yet.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!