• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

A puzzle for the Java gurus...

Status
Not open for further replies.

iapetus

Scary Euro Man
Here's a Java class with one line, which declares a local variable called x, replaced with a comment.

Code:
public class Test {
  public static void main(String[] args) {
    // Missing line of code declaring local variable x...
    System.out.println("Test starting...");
    if (x != x) {
      System.out.println("Unpossible!");
    }
    System.out.println("Test finished.");
  }
}

Compiling and running the class gives the following output:

Code:
Test starting...
Unpossible!
Test finished.

What is the missing line?

If you can't work out the answer immediately, a secondary question: what can you say about the data type of x?
 

maharg

idspispopd
Does Java have a floating point type with a NaN value? :p

[edit] after looking it up, it does and it does:

Java:
public class Test {
  public static void main(String[] args) {
    float x = Float.NaN;
    System.out.println("Test starting...");
    if (x != x) {
      System.out.println("Unpossible!");
    }
    System.out.println("Test finished.");
  }
}
 

iapetus

Scary Euro Man
Got it in one. :) float x = Float.NaN; does the trick.

So much for the reflexivity of the == operator (and by extension, most equals() methods for classes storing floating point values). ;)
 

RevenantKioku

PEINS PEINS PEINS PEINS PEINS PEINS PEINS PEINS PEINS PEINS PEINS PEINS oh god i am drowning in them
float x = Float.NaN;
Although I wasn't the one who realized the right java code, someone next to me knew that.
 
Status
Not open for further replies.
Top Bottom