Your code contains a magic number, and the implied use of the number in the switch statement.
int randomInt = rand.nextInt(20);
The magic number here is 20
. What is that? The number of quotes? Does this mean that you have the switch statement:
switch(randomInt) {
case 0:
....
case 1:
....
case 19:
....
}
I believe so. So, the magic number is a hard-coded number of quotes you support. A simpler solution, that is more managable, is to store your quotes in an array, and the only hard-coded content is the actual quotes:
private static final String[] QUOTES = {
"Life isn't about getting and having, it's about giving and being. –Kevin Kruse",
"Whatever the mind of man can conceive and believe, it can achieve. –Napoleon Hill",
"Strive not to be a success, but rather to be of value. –Albert Einstein",
"Two roads diverged in a wood, and I—I took the one less traveled by, And that has made all the difference. –Robert Frost",
"I attribute my success to this: I never gave or took any excuse. –Florence Nightingale",
"You miss 100% of the shots you don’t take. –Wayne Gretzky",
"I’ve missed more than 9000 shots in my career. I’ve lost almost 300 games. 26 times I’ve been trusted to take the game winning shot and missed. I’ve failed over and over and over again in my life. And that is why I succeed. –Michael Jordan",
"The most difficult thing is the decision to act, the rest is merely tenacity. –Amelia Earhart",
"Every strike brings me closer to the next home run. –Babe Ruth",
....
};
Now you have hard-coded Quotes, and you can add and change them at will, and the QUOTES
array changes along with them.
How do you use this? Well, your main method becomes really simple then:
public static void main(String[] args) {
System.out.println();
Random rand = new Random();
System.out.println(QUOTES[rand.nextInt(QUOTES.length)]);
}
Note that there's no longer any magic numbers. You get the number of quotes from the actual number of quotes, not from a hard-coded value.
if you have 10 quotes it will work fine, if you have 1000 it will work equally well...
Now, if you take in to consideration the comments from @tim, you will also be able to extend the actual String quotes in to Quote and Attribution Objects, and make the program more object-oriented.