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.
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 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 ...
I have written the following code to compute the sum of all the even entries in a LinkedList. However, I keep getting a NullPointerException because of the line where I use (n.getNext).getNext().
Could any of guys tell me as to why this is happening?
Here is the piece of code I'm referring to:
public int sumEven() {
return sumEven(head);
}
// private sumEven helper
private int sumEven(IntListNode n) {
int nodeNumber=1;
int count=0;
if(n.getNext() == null && nodeNumber%2 == 0) {
return n.getValue();
} else if((n.getNext()).getNext() == null && nodeNumber%2 == 0) {
return n.getValue();
} else {
nodeNumber++;
if(nodeNumber%2 == 0) {
count+=n.getValue();
return count+ sumEven(n.getNext());
} else {
return count + sumEven(n.getNext());
}
}
}
Because what if: In the first if statement n.getNext() is null but nodeNumber%2 is not equal to 0
So you go to the next if statement which says n.getNext().getNext() == null where already the first getNext() is null since it passed the first part of the previous if statement but failed the if statement because of the nodeNumber%2 == 0 part.
Ex: nodeNumber = 1 and n.getNext() = null
First if(true && false) => false
Second if(ERROR) Cuz the previous if statement has the first part true which says n.getNext() is null
There are many problems in the code. How about rethink the strategy? If you want to make it recursive, you can assume that the private method sumEven() will always be called with an even node. Then all that private method does is add up whatever that it is called with.
The following code is not tested but shows what I mean.
public int sumEven() {
return sumEven(head,0);
}
private int sumEven(IntListNode n, int total) {
if(n==null) return total;
total += n.getValue(); // sums up running total
if(n.getNext()==null) return total;
return sumEven(n.getNext().getNext(),total); // calls next even node with current running total
}
I'm writing this code in java to scan numerical or alphabetical strings to see if they are consecutive. Everything seems to be working fine until I try to place a boolean in there to return true or false but nothing is happening! What am I missing? THanks! :)
Here it is:
public class Question1 {
public static void main(String[]args){
String s = "gFeD";
isConsecutive(s);
}
public static boolean isConsecutive(String s){
boolean letters;
letters = false;
int counter = 0;
String newS = s.toLowerCase();
for (int i = 0; i < newS.length() - 1; i++){
if (newS.charAt(i) - newS.charAt(i+1) == 1){
return true;
} else if (newS.charAt(i) - newS.charAt(i+1) == -1) {
return true;
}
}
return letters;
}
}
for (int i = 0; i < newS.length() - 1; i++){
if (newS.charAt(i) - newS.charAt(i+1) == 1){
return true;
} else if (newS.charAt(i) - newS.charAt(i+1) == -1) {
return true;
}
this is not what you're after.
You don't want to return true from within the for loop. Not unless you find that the order is not maintained. Else you'll return too early. On the other hand returning false is OK, again if you find that the order is in fact off.
You don't want to check if char - otherchar == 1 or -1 as that's too restrictive. You want to look at > 0 or < 0.
You're not doing anything with the return value. If you want to see it on the console, do System.out.println(isConsecutive(s));. That's why "nothing is happening". It's running properly as you wrote it; it just doesn't produce any visible output.
Just replace last line from main method with System.out.println(isConsecutive(s));. This should work.
You are not printing anything, try System.out.println(isConsecutive(s));
Why am I getting a dead code warning on the i++ in this function ?
InputFilter hexInputFilter()
{
return new InputFilter()
{
#Override
public CharSequence filter(CharSequence source, int start,
int end, Spanned dest, int dstart, int dend)
{
for (int i = start; i < end; i++)
{
if ((source.charAt(i) >= '0')
&& (source.charAt(i) <= '9'))
{
return null;
}
if ((Character.toUpperCase(source.charAt(i)) >= 'A')
&& (Character.toUpperCase(source.charAt(i)) <= 'F'))
{
return null;
}
return "";
}
return null;
}
};
}
There's no chance for the for to loop more than once because you are returning:
return "";
Thus, i++ won't be executed ever and that's why you get a dead code warning. Maybe you want to remove that return ""; and/or put it outside the for.
That is because i++ is normally executed after the end of the for-block, and in your function the end of the for-block will never be reached because in the block you unconditionally return a value.
A for-loop
for (A; B; C) {
D;
}
is internally translated into the following:
A;
while (B) {
D;
C;
}
You can see that if D always returns from the function, C will never be reached. That's what the complaint is about.
You'll only ever execute the loop once because of the return ""; statement.
In your case, the below statement is causing the problem as it runs unconditionally and will always run when the for loop is executed. So it will never reach for i++ so its dead code.
return "";