variable might not be initialized problem. Can someone tell me whats wrong?
when I compile this program it tells me that result might not have been initialized. i have the return types as return result shouldnt this work? can someone tell me how to fix this?
// CheckAnswer.java - This program checks to see if the answer to a test item is correct.
// Input: None.
// Output: Correct or incorrect.
import javax.swing.*;
public class CheckAnswer
{
public static void main(String args[])
{
int intAnswer = 2;
String stringAnswer = "Abraham Lincoln";
boolean boolAnswer = false;
String result;
checkQuestion(intAnswer);
System.out.println("The int answer is " + result);
checkQuestion(stringAnswer);
System.out.println("The String answer is " + result);
checkQuestion(boolAnswer);
System.out.println("The boolean answer is " + result);
System.exit(0);
} // End of main() method.
public static String checkQuestion(int answer)
{
String result;
if(answer==answer)
{
result="correct";
}
return result;
}
public static String checkQuestion(String answer)
{
String result;
if(answer.compareTo(answer)==0)
{
result="correct";
}
return result;
}
public static String checkQuestion(boolean answer)
{
String result;
if(answer=false)
{
result="correct";
}
return result;
}
} // End of CheckAnswer class.
Re: variable might not be initialized problem. Can someone tell me whats wrong?
Code java:
public int doStuff(boolean bool) {
int value;
if(bool) {
value = 10;
}
return value;
}
What value should be returned when false is passed in as a parameter? You have the same issue in your code.
Re: variable might not be initialized problem. Can someone tell me whats wrong?
Quote:
Originally Posted by
Junky
Code java:
public int doStuff(boolean bool) {
int value;
if(bool) {
value = 10;
}
return value;
}
What value should be returned when false is passed in as a parameter? You have the same issue in your code.
Doesn't java initialize all primitive data types itself?
Well, talking about String, that must be initialized.
Junky's post is valueable to you as a logic, if you consider value as a String variable.
Re: variable might not be initialized problem. Can someone tell me whats wrong?
The difference is that a local variable in a method is different from a class variable.
The local variable could go on the stack and not be initialized when the method is called.
The class level variable gets a value when the class is created.
Write a small test program and see if the above is true.