• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Xavier Davis
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Bartender
Posts: 1302
24
C++ Java Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 50175
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic