Thursday, May 14, 2009

Puzzle 24 - Recessional Increment (Code Complete - 2)

Language – Java | Type – Problem (Code) | Last date 17-May-2009 12:00 p.m. IST | Points 2

Without much ado - here is the next puzzle!

package com.twisters;
public class UnIncrement{
public static void main(String[] args) {
int x = 0;
x
++;
System.out.println(
"X is : " + x);//This must print 'X is 0'
}
}

Get the System.out.prinltn() to print 'X is 0' at line 6.
You may add (but not delete) any additional amount of code.

Sounds too simple doesn't it? Time to throw in a few additional clauses - generously I’ll just add one.
"You can just add two characters to the above code to get it to work - any two characters buts that all"

If you’re wondering why this puzzle is so easy - its because I have a few plans up my sleeves to make this more interesting in my next post-:)

Link of the day - http://javatutorialsworld.blogspot.com/2009/05/simple-java-twisters.html - have fun with the increment operator and see if you can get all six correct!

Got an answer? Do leave it here.

8 comments:

  1. 1 package com.twisters;
    2 public class UnIncrement{
    3 public static void main(String[] args) {
    4 int x = 0;
    5 x = x++;
    6 System.out.println("X is : " + x);//This must print 'X is 0'
    7 }
    8 }

    I just was involved with x = x++ discussions on Javaranch :).

    ReplyDelete
  2. For this to print "X is O", we must change this:

    System.out.println("X is : " + x);

    into this:

    System.out.println("X is : " + --x);


    If you use the x--, it will print 1 before changing value of x.


    Cheers, Bernardo.

    ReplyDelete
  3. 1 package com.twisters;
    2 public class UnIncrement{
    3 public static void main(String[] args) {
    4 int x = 0;
    5 x++--;
    6 System.out.println("X is : " + x);//This must print 'X is 0'
    7 }
    8 }

    ReplyDelete
  4. 1 package com.twisters;
    2 public class UnIncrement{
    3 public static void main(String[] args) {
    4 int x = 0;
    5 x++--;
    6 System.out.println("X is : " + x);//This must print 'X is 0'
    7 }
    8 }

    ReplyDelete
  5. System.out.println("x = "+--x);

    ReplyDelete
  6. public static void main(String[] args) {
    int x = 0;
    x++;
    System.out.println("X is : " + --x);
    }

    ReplyDelete
  7. System.out.println("X is : " + --x)

    ReplyDelete
  8. public class UnIncrement{
    public static void main(String[] args) {
    int x = 0-1;
    x++;
    System.out.println("X is : " + x);//This must print 'X is 0'
    }
    }

    or

    public class UnIncrement{
    public static void main(String[] args) {
    int x = 0;
    x++;
    System.out.println("X is : " + --x);//This must print 'X is 0'
    }
    }

    ReplyDelete

Solution for this question?