I am trying to write a program for my java class. The program is supposed to ask the user what the lengths of the sides of a triangle are and then determine whether or not the triangle is valid or not. The program is also supposed to calculate the area of the triangle. I'm also trying to get it to loop 3 times. Everytime i try to run the code below i get errors saying that variable may not have been initialized (area and output). I put an arrow on the lines that I get errors from and highlighted the variable that isn't getting initialized.
1) When you post source code, it helps if you post it inside "code" tags. There are little buttons above where you enter your post that let you make things bold, underlined, etc. One of them will drop the UBB tags in the post, and then you can put your source between them. It will preserver the formatting, making it much easier for old people like me to read.
2) It also helps to post the EXACT error message you get - just cut-n-paste it!!! It tells the exact line number and often will show the spot where the error is (or where the compiler THINKS it is, which is not always the same thing).
3) Convention says classes should have their first letter capitalized, so this should be called "MyTriangle". This is a minor nit-pick.
Now...as to your problem...The error message is exactly correct. You have a variable 'area' declared on line 12, but you never initialize it to anything. this can be fixed by changing line 12 to
double area = 0;
Of course, one you do that (and fix the other variable in the same way), you'll find other errors - like the fact that you never CHANGE the value of the area variable - but we can fix those once you find them.
Your 'output' variable has also never been initialized. it is an object, so you can't quite do it the same way. Although, since it is a String object, you do get to use a shortcut. you can intialize it to the empty string:
String output = "";
The difference is that without the part I added, you have said "I need something that will hold a string", but you never created the string.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I went ahead and put in the code tags for you, and cleaned up the yellow color - my eyes simply couldn't read it.
Joined: Feb 15, 2011
Ok, thank you very much! This is my first time ever posting on this site so I had no idea how to post code correctly and I did not think the the highlight would be so hard to read. Thank you for fixing my post into a much cleaner style, I'll have to remember that if I ever have to post here.