Results 1 to 4 of 4
Thread: Java, Random and ?
- 10-07-2012, 10:19 PM #1
Member
- Join Date
- Oct 2012
- Posts
- 2
- Rep Power
- 0
Java, Random and ?
Can you tell me what the "?" mark is in this code (i.e. what its called)
Random rand = new Random();
int choice = (rand.nextInt(100)<75) ? 1:0;
When the code is run it returns either 1 or 0.
It returns 1 75% of the time.
I have played with the 1:0 values if you change it to 5:10 for example it returns the number 5, 75% of the time.
I want to understand what the ? is doing. I get that it some how identifies that of the two values it returns the first one 75% more than the second one.
And if you change the 75 to 25 it would then return the first value (1) 25% of the time vs. second value.
But I can't find any documentation on the ? or what other options I could use in place of it.
Thanks
- 10-07-2012, 10:26 PM #2
Member
- Join Date
- Oct 2012
- Location
- Tempe, Arizona
- Posts
- 77
- Blog Entries
- 12
- Rep Power
- 0
Re: Java, Random and ?
The question mark is just a different form of the if statement. The following two snippets of code do exactly the same things:
Java Code:public Foo generateFoo(int threshold) { if(threshold > MIN_THRESHOLD) return new Foo(); else return null; }Java Code:public Foo generateFoo(in threshold) { return (threshold > MIN_THRESHOLD) ? new Foo() : null; }Last edited by Fubarable; 10-07-2012 at 11:25 PM. Reason: Foo return type added
- 10-07-2012, 10:32 PM #3
Member
- Join Date
- Oct 2012
- Posts
- 2
- Rep Power
- 0
Re: Java, Random and ?
Thank you now I remember that aspect. Have a great day.
- 10-08-2012, 04:07 AM #4
Re: Java, Random and ?
It's called a ternary expression.
Not really, no. The ternary expression is a value expression which must evaluate to a valid value.
This won't compile, because void isn't a valid value:dbJava Code:... { boolean condn = false; // or true condn ? setInt(0) : setInt(1); } void setInt(int value) { ... }Why do they call it rush hour when nothing moves? - Robin Williams
Similar Threads
-
Using java.util.Random to choose a random sentence and print it
By skylerrivera17 in forum New To JavaReplies: 0Last Post: 01-23-2012, 09:12 AM -
Java random number
By Mezgrath in forum New To JavaReplies: 3Last Post: 11-22-2009, 06:15 AM -
how i use the random class to random the cards i have
By yanipao in forum New To JavaReplies: 14Last Post: 10-19-2009, 10:57 AM -
How do I generate random numbers in a certain range using the random class?
By frasifrasi in forum New To JavaReplies: 8Last Post: 04-19-2009, 05:50 PM -
random numbers without random class`
By carlos123 in forum New To JavaReplies: 4Last Post: 01-17-2008, 10:44 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks