Translation staff: Anchor
Translation Date: November 20, 2013
Source text link: A puzzle from "a Brief History of the (Java) world and A Peek Forward" presented by Neal Gafter
Here's a Java riddle from Neal Gafter's speech:
Import Java.util.Random;
Rhymes, rhyme public
class Rhymes {
private static Random rnd = new Random ();
/**
* What could be the output of the following program?
* (a) Pain, Gain or main (according to each random number)
* (b) Pain or main (according to random number)
* (c) Main (always this)
* (d) None of the above is not
* * * public static void Main (string[] args) {
StringBuffer word = null;
Switch (Rnd.nextint (2)) {case
1:word = new StringBuffer (' P ');
Case 2:word = new StringBuffer (' G ');
Default:word = new StringBuffer (' M ');
}
Word.append (' a ');
Word.append (' i ');
Word.append (' n ');
SYSTEM.OUT.PRINTLN (Word);
}
Which is the correct answer?
The correct answer is D.
There are three flaws in the program:
1. Obviously, there is no break in the switch statement
2. Nextint (2) The result returned is only 0 or 1
3. ' P ', ' G ', ' M ' is a char-type hand, not a string object, so it is automatically converted to an int and a constructor that does not conform to the expected function is invoked.
For more information, refer to the books of Joshua Bloch and Columbia (Neal gafter), "Java FAQ"
Related reading:
Ten common Java string issues
Declaration, initialization and scoping for Java Java Code:given range, return an array of N random numbers constructor C An Throw exceptions in java!