Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variables not initalizing

 
John Walker
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone, I'm trying to make a little program that will output a random card from a deck. I just started but I'm getting the error that the card variable might not be initalized. What am I doing wrong?
public class Cards {

public static void main (String[]args) {
int number;
String card;
number = (int)(Math.random()*4+1);

if (number == 1)
card = ("Ace");
else
if (number == 2)
card = ("2");
else
if (number == 3)
card = ("3");
else
if (number == 4)
card = ("4");
else
System.out.println(card);

}
}
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What gets assigned to "card" if "number" is not 1, 2, 3, or 4? Nothing, right. But you're printing the value in that case. Java won't let you read from a variable that's never been assigned to.
There are several ways to deal with this. One would be to initialize "card" when you declare it:

Another would be to add a bare "else" case to the end of your chain of if-else's to assign a value if one hasn't been assigned so far, or throw an exception.
Another would be to change the if-elses to a switch statement, and include a default case that assigns some value or throws an exception.
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For what it's worth, Java guarantees that all instance variables (static or otherwise) will be initialized. All objects become "null", booleans are "false" and all other primitives will be zero (0, 0L, 0.0, as appropriate). I think it's a good idea to explicitly initialize them, but the JVM will take care of it.
However local variables, such as "number" and "card" in your class, must be explicitly initialized as Ernest pointed out.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic