This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes java:22: error: variable x might not have been initialized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "java:22: error: variable x might not have been initialized" Watch "java:22: error: variable x might not have been initialized" New topic
Author

java:22: error: variable x might not have been initialized

Xavier Davis
Greenhorn

Joined: Feb 04, 2013
Posts: 1


SecretFormula.java:22: error: variable x might not have been initialized
double formula = Math.sqrt((Math.abs(Math.pow(x,4) - 5 * Math.pow(x,3))) + 7 * Math.pow(x,2) + 5 * x);
The arrow is under the x with the 4
SecretFormula.java:25: error: variable theValue might not have been initialized
System.out.print("Enter a value for x: " + theValue);

2 errors
Stevens Miller
Ranch Hand

Joined: Jul 26, 2012
Posts: 523
    
    3

What are you trying to accomplish, Xavier? It's quite easy to see why you have the two errors that you do, but that makes me wonder what you were expecting and why. Are you trying to make "formula" into some kind of method?

Regardless, consider the fact that you are using x before you ask the user to provide any input (and, when you do, you are storing the user's input in theValue, not x).
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37950
    
  22
Welcome to the Ranch

You have been given the answer; unlike fields which default to 0, local variables do not have default values and must be definitely assigned before they can be used.
You should use the code button, which I have applied retrospectively and you can see how much better the post looks Unfortunately it highlights the long line (5). You should divide that line into several lines. You should also divide the multiple declaration; it is a lot easier to read if you declare every variable in its own line with its own semicolon. And don’t declare variables which you are not using.
Don’t use Math.pow for small whole numbers. Avoid Math.pow(i, 2) if possible. Write i * i. Much better performance and possibly precision, as long as you don’t suffer an overflow.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: java:22: error: variable x might not have been initialized
 
Similar Threads
Quadratic formula result problem
Root Finding
variable counter might not have been initialized
(new to java)variables might not have been initialized
squaring