I'm pretty new to Java. Eclipse is giving me the error
This method must return a result of type
I want to return the String str, if I put str after all the for-loops I would get local variable not initialized. How could I code it so that
public String getQuadraticFactors() {
String str;
ArrayList<Integer> prFactors = new ArrayList<Integer>();
ArrayList<Integer> qsFactors = new ArrayList<Integer>();
ArrayList<Integer> p = getPRIntegerFactors(a), r = getPRIntegerFactors(a), q = getQSIntegerFactors(c),
s = getQSIntegerFactors(c);
System.out.println(p + "*********" + q);
System.out.println(p.get(0));
// String str2 = "jjjhljl";
String str2 = "(" + p + "x + " + q + ")(" + r + "x +" + s + ")";
for (int k = 0; k < p.size(); k++) {
// System.out.print(k);
for (int l = 0; l < q.size(); l++) {
// System.out.print(k);
for (int m = 0; m < p.size(); m++) {
for (int n = 0; n < q.size(); n++) {
if (p.get(k) * r.get(m) == a && p.get(k) * s.get(n) + q.get(l) * r.get(m) == b
&& q.get(l) * s.get(n) == c) {
System.out.println(a);
System.out.println(p.get(k) * r.get(m));
return str = "(" + p.get(k) + "x + " + q.get(l) + ")(" + r.get(m) + "x + " + s.get(n) + ")";
}
}
}
}
}
}
2 Answers
there is a slight possibility that you will never hit your return statement. To fix this, just add a return statement to the very bottom of your method that returns a empty string or whatever value you would like to send to say that
if (p.get(k) * r.get(m) == a && p.get(k) * s.get(n) + q.get(l) * r.get(m) == b
&& q.get(l) * s.get(n) == c)
this if statement is false for all cases. Sometimes you will never run into a situation where this if statement is false, but the JVM just needs reassurance that it has something to return if it is false.
Actually you need to have an alternative when some of your for-loops don't run. Just initialise your str with some value of better yet, check it at the bottom. If it is null throw an exception or initialize it (depending on your code style). When you check before returning it will always have a value (or you throw an exception).