Where is the problem? If I use a variable it works just fine, but I am missing something.
public boolean xyzThere(String str) {
if (str.length() > 2){
if(str.startsWith("xyz")){
return true;
} else {
for (int i = 1; i < str.length() - 2; i++){
if(str.substring(i, i + 3).equals("xyz") && !str.substring(i - 1, i).equals(".")) {
return true;
} else {
return false;
}
}
}
} else {
return false;
}
}
This condition needs a return statement as the code inside for loop may not be reachable.
else {
for (int i = 1; i < str.length() - 2; i++) {
if (str.substring(i, i + 3).equals("xyz") && !str.substring(i - 1, i).equals(".")) {
return true;
} else {
return false;
}
}
}
Because it might be possible that none of your outer if condition succeed , So Compiler is making sure that your program doesn't get stuck into the function , by throwing the missing return statement error
So try this way :
if(condition){
return false;
}
elseif(condition){
return true;
}
return false; <--- Now compiler is assured that function will return something
Assuming the return type is boolean
The Java compiler will not evaluate the conditions to determine if one of if condition and an else if condition will be guaranteed to run.
Without the conditions, the compiler see the possibility of neither condition being true, and in that case, nothing is returned. There are not return statements past the else if. This occurs even if we see that logically one of them will be true.
Just turn your else if into an else to satisfy the compiler.
else {
return false;
}
Now the compiler will see that there is a return statement in all possible execution paths.
In these cases, sometimes I comment out the condition to let readers know the real intent.
else // if (str.length() < 3)
{
return false;
}
Update:
Something similar is occurring inside the for loop. The compiler won't assume that at least one iteration of a for loop will occur. If the for loop body is never entered, then the else block ends, and the body of the outer if block ends without a return statement`.
You must provide a return statement after the for loop, in case the for loop is never entered.
Now it is compiling:
public boolean xyzThere(String str) {
if (str.length() < 3){
return false;
} else {
if(str.startsWith("xyz")){
return true;
} else {
for (int i = 1; i < str.length() - 2; i++){
if(str.substring(i, i + 3).equals("xyz") && !str.substring(i - 1, i).equals(".")) {
return true;
} else {
}
}
return false;
}
}
}
Related
public static boolean hasGreaterDoWhile(List<Integer> numbers, int number) {
int d = 0;
do {
if (numbers.get(d) > number){
return true;
}
d++;
}
while (d < numbers.size());
return false;
}
(JAVA only)
P.s This is a function i have tried, in order to check the first argument, and if it contains a number that is larger than the second argument, it will then return true, and flase otherwise.
Note that it is using do while loop. I just don't know which part of this code i have done wrong, because the system keeps telling me that "java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0".
Thank u, any hint will be much appriciated.
your list of Integers is empty. you can't access an index of an empty list:
public static boolean hasGreaterDoWhile(List<Integer> numbers, int number) {
int d = 0;
if (numbers.isEmpty()) return false;
do {
if (numbers.get(d) > number){
return true;
}
d++;
}
while (d < numbers.size());
return false;
}
A do-while control block works as follows:
Execute the do block
Check the condition. If it holds, return to (1)
Notice the order of this flow. Unlike a standard while, do-while will always execute one iteration before checking the condition. Therefore, for an empty list you will always try to access the 0-index element of the table, which does not exist, hence the error. You can use a while loop to avoid this:
public static boolean hasGreaterDoWhile(List<Integer> numbers, int number) {
int d = 0;
while (d < numbers.size()) {
if (numbers.get(d) > number){
return true;
}
d++;
}
return false;
}
You should check whether the collection is empty
like this
if(numbers == null || numbers.isEmpty()) {
return false;
}
int d = 0;
do {
if (numbers.get(d) > number){
return true;
}
d++;
}
while (d < numbers.size());
return false;
I'm trying to figure out how to catch a numberformat exception error within my code such that if the user inputs a letter within a string and my program tries to parse it to an int my program won't throw up an error but instead stop and return a Boolean value. I'm also trying to understand that if the try statement works I'd like it to continue to execute the following code.
if (counter == 3) {
int compare;
boolean check = true;
String[] newip = IpAddress.split("\\.");
if (newip.length == 4) {
for (int index = 0; index < newip.length; index++) {
//There should be a try statement here.
// if the try statement fails then I'd like for it to catch
// the numberformatexception and evaluate my boolean to
//false;
//but if it passes I'd like for it to continue to execute
//the following code.
compare = Integer.parseInt(newip[index]);
if (compare >= 0 & (compare <= 255)) {
check = true;
}
else{
check = false;
}
}
if (check)
return true;
else
return false;
}
else {
check = false;
return check;
}
}
else{
return false;
}
}
Surround that line with try/catch:
try {
compare = Integer.parseInt(newip[index]);
} catch (NumberFormatException e) {
check = false;
}
and then:
if (check) {
if (compare >= 0 & (compare <= 255)) {
check = true;
} else {
check = false;
}
} else {
return false;
}
Instead of catching NumberFormatException, you can use NumberUtils from commons-lang 3.x to check if the input is a number.
NumberUtils.isNumber(newip[index])
However as per the documentation, it would be deprecated in 4.x and you would need to use isCreatable
NumberUtils.isCreatable(newip[index])
I want to return Vector according to if block but the code gives me the following error: Add return statement.
Is it possible to write return statement in if block?
public static int[] zeroVectorBinning1( ImageFloat32 angle,ImageFloat32 Magnitude )
{
for (int NumberOFChanks=0;NumberOFChanks<locations_original.size();NumberOFChanks++)
{
for(int i=0;i<angle.getHeight();i++)
for(int j=0;j<angle.getWidth();j++)
{
int orientaionVal=(int) angle.get(j, i);
if(orientaionVal<=0)
{int magnitudeVal=(int) Magnitude.get(j, i);
int[] Vector = new int[19];
Vector=zeroVector(19);
Vector[0]=magnitudeVal;
return Vector;
}
else if(orientaionVal<=20)
{int magnitudeVal=(int) Magnitude.get(j, i);
int[] Vector = new int[19];
Vector=zeroVector(19);
Vector[1]=magnitudeVal;
return Vector;
}
else(orientaionVal >= 0 && orientaionVal <=20)
{
int magnitudeVal=(int) Magnitude.get(j, i);
int[] Vector = new int[19];
Vector=zeroVector(19);
Vector[0]=magnitudeVal;
Vector[1]=magnitudeVal;
return Vector;
}
}
}
}
There's nothing wrong in having return statements in if blocks, but your method must have a return statement in any execution path.
Your for loops may never be executed (if, for example, locations_original.size() is 0), in which case none of the if blocks that contain the return statements will be reached. Therefore you must add a return statement following the loops.
Yes,
But your function still not return anything in the end, so you have to return something, even null.
So when you call this function, it should ne looking like this:
int[] fuctionResult = zeroVectorBinning1(....);
if (fuctionResult != null){
....
}
You could resolve this in two ways:
At the end either throw an exception just before completing the method.
Or at the end just return null.
Reason why compiler is complaining because, if locations_original.size() returns 0 then this method would never return anything which contradicts with what you said in your method that it will return an int array.
It is possible. But you need a return statement for every cases. Also if your for loop is never executed.
so add return null; at the end of your method.
Yes it is possible. Follow the code snippet for explanation.
public class TestSample {
public static void main(String... w){
int h = new TestSample().call();
System.out.println(h);
}
public int call(){
int j =0;
for(int i=0;i<10;i++){
if(i==5){
return i;
}
}
return j;
}
}
This prints 5.
public int getValue(){
final int value = 3;
if(value==1){
return 1;
}
else if(value==2){
return 2;
}
else if(value==3){
return 3;
}
else{
return -1;
}
// no return because "else" covers all cases
}
In this case you have an "else" at the end, so every case is covered. but if you leave the else ...
public int getValue(){
final int value = 3;
if(value==1){
return 1;
}
else if(value==2){
return 2;
}
else if(value==3){
return 3;
}
return -1;
// ... you have to return something at the end of the method, because value could be >3 or < 1 and the code under the last else if will be executed
}
The problem is your if/else-if/else parse is not complete, what does else with a condition like:
else(orientaionVal >= 0 && orientaionVal <=20)
mean? It's odd. Just omit the condition (orientaionVal >= 0 && orientaionVal <=20) of the last else sentence (and it's not logically correct when orientaionVal is 0 or 20), or there will be no default else in the scope.
When return in the scope of a if sentence, we must make sure that under any condition there is a return, so:
Make a default return out of the if-else scope
Or be sure that the condition judgement is complete and there is a return under any condition.
So
Correct:
if(condition){
return;
}
return;
Correct:
if(condition){
return;
}else if(anotherCondition){
return;
}else{
return;
}
Wrong:
if(condition){
return;
}
// no return ...
Wrong:
if(condition){
return;
}else if(anotherCodition){
return;
}
// no return ...
public boolean Winner() {
for (int z = 0; z < 3; z++) {
if (board[z] != null && board[z] == board[z+3] && board[z] == board[z+6]
) {
return true;
}
}
for(int i=0; i<7;i+=3){
if (board[i] != null && board[i] == board[i+1] && board[i] == board[i+2]) {
return true;}
}
}
It returns me this error: this method must return a result of type boolean. What am I doing wrong?
Right now, the function isn't guaranteed to return a boolean, because it's possible that neither of the if statements will ever be entered.
You could fix it like this (but only do this if it's actually what your logic needs!):
public boolean Winner() {
for (int z = 0; z < 3; z++) {
if (board[z] != null && board[z] == board[z+3] && board[z] == board[z+6]
) {
return true;
}
}
for(int i=0; i<7;i+=3){
if (board[i] != null && board[i] == board[i+1] && board[i] == board[i+2]) {
return true;}
}
return false;
}
The Java compiler doesn't make assumptions that a for loop will have an iteration or that an if statement block will run.
There are execution paths where there is no return statement. What happens if the execution path doesn't execute any of the existing return statements and drops to the bottom? There isn't a return there.
Add a return at the bottom.
All possible ways that the method can exit need to return something. If your code makes it through both for loops without having an if condition evaluate to true, then you need a return at the end that specifies what gets returned.
The compiler is not aware that at least one of the loops will be executed. It takes into account all the possibilities of the execution and one of them is that neither of the loops will be executed and in that case there is no return statement. So insert a return statement out of the loops as well.
The answer to this question is easy. It happened to me too. The problem in your code is that you don't say to the computer what to do in case that the "if" statement is wrong, so you just have to add an "else {return false}" to every "if". Another tip is: please make your code cleaner and readable.
public boolean Winner() {
for (int z = 0; z < 3; z++) {
if (board[z] != null && board[z] == board[z+3] && board[z] == board[z+6]) {
return true;
} else {
return false;
}
}
for (int i=0; i<7; i+=3) {
if (board[i] != null && board[i] == board[i+1] && board[i] == board[i+2]) {
return true;
} else {
return false;
}
}
}
Okay, so my question is regarding boolean returns. For my Comp Sci homework, I have to make a course registration program using methods, and one of them is an add course method. Basically, you search for the class in a catalog, and if it matches you add it to the students schedule and return a boolean value of true. I did this, but for some reason it is giving me an error. Here is the code:
public static boolean addCourse(
Course[] catalog,
Course[] mySchedule,
int myNumCourses,
int dept,
int courseNum)
{
int j;
int i;
int k;
int deptCat;
int courseNumCat;
Course courseAdd = null;
char checkDay;
int checkTime;
if (mySchedule.length == myNumCourses) {
return false;
}
for (i = 0 ; i < catalog.length ; i++) {
Course course = catalog[i];
deptCat = course.getDepartment();
courseNumCat = course.getCourseNumber();
if (deptCat == dept && courseNumCat == courseNum) {
courseAdd = catalog[i];
break;
}
else continue; }
for (j = 0 ; j < myNumCourses ; j++) {
if (mySchedule[j] == null) {
mySchedule[j] = courseAdd;
return true;
}
else continue;
}
for (k = 0 ; k < mySchedule.length ; k++) {
Course course = mySchedule[k];
if (course != null) {
checkDay = course.getDay();
checkTime = course.getPeriod();
if (checkDay == courseAdd.getDay() && checkTime == courseAdd.getPeriod()) {
return false;
}
}
else continue;
}
}
Why doesn't it recognize the boolean return values? Is it because I placed them inside a loop?
You need to place a return-statement at the end of your method, even if you might know it will never be reached (the compiler is not smart enough to know that, which explains the error).
For instance, even this will not compile:
public static boolean foo() {
if (true)
return true;
}
unless we add a final return statement. What you have is analogous.
There is nothing wrong with putting your return values in loops, however, the compiler sees no guarantee that this method will return a value and thus raises an error. At the very end of the method you need to return either true or false, whichever is most appropriate. All of your returns are within conditionals and therefor could fail to execute leaving your function with no return statement.
You must explicitly return a boolean(true/false) in ALL code path.Because your function's return type is "boolean".
In your case,you must add a return statement after the last loop.
If you don't want to write to many "return xx" statement,you can change the return type of this function to "void".And throw Exception in the false cases.
I think there is a problem with the last loop. If the condition for returning false is never met, it continues until it get to the end of the schedule, without returning anything. If you were to add a return at the end of the method this loop could fall through to it. Did you mean to return true after the loop, if no 'return false' is executed?
for (k = 0; k < mySchedule.length; k++) {
Course course = mySchedule[k];
if (course != null) {
checkDay = course.getDay();
checkTime = course.getPeriod();
if (checkDay == courseAdd.getDay()
&& checkTime == courseAdd.getPeriod()) {
return false;
}
} else
continue;
}
Where ever you are using if statement its possible else also must return or flow must go to another return.ELSE is missing with return.