Using loops to return in a method - java

So, I need to return either a position in an array or a -1 if the goal number is not found. The problem is when I use return inside an if else statement, I get an error because the program will not go into the if loop. Here is my current code:
public int search(int num1)
{
for(int i=0;i<scores.length;i++)
{
if(scores[i]==num1)
{
return i;
}
else
{
return -1;
}
}
}
This keeps giving me an error saying no return statement. Is there a way to do this logic without the error?
thanks guys

If the for loop is not entered, then there is no return statement. This could happen if scores.length is 0. You must supply a return statement in all cases of execution, or the compiler will catch a case without a return statement and give a compiler error.
Move the return -1 after the for loop, so that you only return -1 if you went through the entire loop and didn't find num1. That also means that the else block is unnecessary -- remove it.

it gives you error because it might think that the loop might not be executed. in order for it to run it has to be a return statement outside a loop or an if statement.
here is an adjustment i did with your code.
public int search(int num1) {
int x = -1;
for(int i = 0; i < scores.length; i++) {
if(scores[i]==num1) {
x = i;
}
}
return x;
}

Related

Studying if/else vs if/if statement

I was trying to write a code where all the 0s will be moved to the right of the array. I just used a left and a right pointer.
public class Solution {
public int[] moveZero(int[] array) {
// Write your solution here
if (array.length==0) {
return array;
}
int left=0;
int right=array.length-1;
while (left<=right) {
if (array[left]!=0) {
left+=1;
}
if (array[right]==0) {
right-=1;
} else {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
left+=1;
right-=1;
}
}
return array;
}
}
I know here I should use the if/else if instead of if/if, that's why I have the index out of the bound error. But I don't understand why? If I have the if/if statement, what's the difference does that make rather than using if/else if in this question?
if (condition1) {
a();
} else if (condition2) {
b();
} else {
c();
}
means the same as
if (condition1) {
a();
} else {
if (condition2) {
b();
} else {
c();
}
}
So else if is just shorthand for an else with an if inside.
To understand why your code throws an ArrayIndexOutOfBoundsException, the easiest way is stepping through the code in a debugger (consult the documentation of your development environment for how to do this).
Alternatively, you can pretend you are a computer, and execute the program with pen and paper to figure out where your program goes off the rails. However, using a debugger is easier once you know how to use one.
I don't think there's any reason to use if/else instead of if/if, they both have their place. In an if/if statement, if the second if statement relies on the previous being false, then it should be converted to an if/else statement. If the else statement in an if/else statement has nothing to do with the if statement before it, then it should be converted into two separate if statements.
As an example of when to use an if/else statement (to do the same thing yours does):
public class Solution {
public int[] moveZero(int[] inputArray) {
int[] outputArray = new int[inputArray.length];
int left = 0;
int right = inputArray.length - 1;
for (int num : inputArray) {
if (num == 0) {
outputArray[right] = num;
right --;
} else {
outputArray[left] = num;
left ++;
}
}
return outputArray;
}
}

Java compiler error 'missing return statement' when using recursion

I am implementing a method to traverse a trie (more specifically, I am trying to count the number of leaf nodes. The edges going into these leaf nodes all have a terminator symbol '#').
I am using Java and am getting an error when using this method:
public int traverse(Node n){
for(int i=0; i<n.getNumEdges(); i++){
if(n.getEdgeChar(i) == '#'){
return 1;
}
else{
return traverse((n.getEdge(i)).getNode());
}
}
}
I do understand why I'm getting this error, but how do I get around it? Initially, I thought it best to pass noLeaves as a parameter, but after doing some research I found that the above code is considered better practice. I just don't know how to get around this compiler error. Any help would be appreciated!
There may be a case when n.getNumEdges() equals to 0 and the for statement won't execute. You should return a default value
return 0;
or throw an exception if such behaviour is considered illegal:
throw new IllegalArgumentException("There are no edges in the node!");
I am guessing a bit here, but I think the following is what you intended?
public int traverse(Node n){
int numOfLeaves = 0;
for (int i=0; i<n.getNumEdges(); i++) {
if(n.getEdgeChar(i) == '#') { // leaf
numOfLeaves += 1;
}
else {
numOfLeaves += traverse((n.getEdge(i)).getNode());
}
}
return numOfLeaves;
}
This will sum the results of the recursive calls for all edges and return the sum. # is assumed to indicate a leaf and will count as 1 in the sum rather than doing a recursive call.
When you declare your function returning any value(in your case int), it must return any integer by the end of code. In your method, it is possible that function may not return anything the node is empty or null.
To rectify the error, do following changes to your code
public int traverse(Node n){
int returnValue=-1;
for(int i=0; i<n.getNumEdges(); i++){
if(n.getEdgeChar(i) == '#'){
returnValue=1;
break;
/*return 1;*/
}
else{
returnValue=traverse((n.getEdge(i)).getNode());
break;
/*return */
}
}
return returnValue;
}

How to tell if an int has been changed

I want to know how to tell if an int has been changed (during the program).
Like with an if statement.
int i = 2;
int a = 1;
while(1 < 2) {
if(i % 100 == 0) i++;
}
if(i //Then checks if it changed) {
System.out.println("Changed :D");
}
Is there a way to tell if the variable i is changed DURING the program?
Since this is Java, are these variables data members of a class? In that case give them private access and provide getters and setters. Your setter can notify you if you so desire.
int i = 0;
boolean valueChanged = false;
while(some good condition) {
if (i % 100 == 0) {
i++;
valueChanged = true;
}
}
if(valueChanged) {
System.out.println("Changed :D");
}
// Your int variable
int i = 0;
// A scratch variable
int prev_value_of_i = i;
// Call this code to check whether i has changed since last call
if(i != prev_value_of_i) {
System.out.println("Changed :D");
prev_value_of_i = i;
}
Keep track of the original value of i in a separate variable and compare i to that?
This seems redundant, since the programmer should know when and where values are stored. If you don't, maybe step through with a debugger? #shoover's answer is the most flexible, handling however many unexpected times you might change the value without requiring adding lines of code inside your infinite loop.
class TalkativeInt{
private int x;
TalkativeInteger(int x){
this.x = x;
}
public void set(int a){
System.out.println("Changed!! "+x+" to "+a);
x = a;
}
public int get(){
//System.out.println("Accessed - that tickles");
return x;
}
}

Make a for loop method with if statements return the correct "return" without array?

I am doing some java exercises and I am trying to make a method that counts to 100 and prints the number each time the for loop "loops". The exception is that it will print "Fizz" when the number is divisible by 3 and "Buzz" when the number is divisible by 5.
Now, I have three return types in my method that is gonna return a String. However, the error says I do not return a value. I am aware that I have to make it return a String outside the for loop but I am having some trouble figuring out how I should get to return the value that I want. I am also aware that I could use arrays or even arrayList to fix this problem but I think its possible without that and I would like to try doing so. Any help would be very appreciated! Here is the code:
package etcOvaningar;
public class ovning1 {
public static String fizz ="Fizz!";
public static String buzz ="Buzz!";
public static String countDown(){
for (int number = 0; number < 100; number++){
if (number%3 == 0){
return fizz;
}
else if (number%5 == 0){
return buzz;
}
else
return String.valueOf(number);
}
//I need to insert a return here I suppose, but I want the correct return from the if and else //statements
}
public static void main(String[] args){
}
}
Don't "return" in the loop, but rather print. When you return, the method exits, and the loop loops no more. If you simply print the necessary text, the for loop will continue to loop until it reaches its natural end condition.
public static void countDown(){
for (int number = 0; number < 100; number++){
if (number % (3*5) == 0) {
System.out.println("fizzbuzz");
} else
if (number % 3 == 0){
System.out.println("fizz");
} else
if (number % 5 == 0){
System.out.println("buzz");
}
}
}
Note as per Martin Dinov, this method should be declared to return void, nothing.
Your code won't compile because method countdown needs return value below the for loop.
However whatever you return value you put below the for loop won't matter because your countdown method will always return "Fizz!"
This is another way to do what you want to do. Perhaps, more of what you really should be doing.
private static String fizz ="Fizz!";
private static String buzz ="Buzz!";
public static void main(String[] args){
for (int number = 0; number < 100; number++){
String word = checkNumber(number);
System.out.println(word);
}
}
private static String checkNumber(int number){
String value = "";
if (number%3 == 0){
value += fizz;
}
if (number%5 == 0){
value += buzz;
}
if (value.isEmpty()) {
value = String.valueOf(number);
}
return value;
}
Points to note:
Start your methods and fields as private and upgrade their visibility as you further develop your program and your needs change. This helps keep the code clean and the exposure to the minimum.
Try not to have print statements in methods (unless they are specifically designed for printing messages). They should take an input, process the input and return an output. Nothing more, nothing less.
Understand the difference between if / else if / else and if / if / if. The number 15 is divisible by both 3 and 5.

Java recursion count

First of all this is not homework. Just me practicing.
I'm trying to recursively determine the number of times "hi" appears in the given string, but in every case it skips to the last else if statement and things the string is empty. Any ideas?
Basically,
if(string starts with "hi")
increment count by 1 and recurse with the string after the 2nd index to skip over the "hi" it just counted
else if(string does not start with "hi" and string is not empty)
recurse with the string after its 1st index to see if it starts with "hi" the next time around.
else if(string is empty)
Print("End of text reached")
return count;
public class Practice {
public int recur(String str, int counter){
int count=counter;
if(str.startsWith("hi")){
count++;
recur(str.substring(2),count);
}
else if((!str.isEmpty())&&(!str.startsWith("hi"))){
recur(str.substring(1),count);
}
else if(str.isEmpty()){
System.out.println("End of text reached");
return count;
}
return count;
}
public static void main(String args[]){
String str="xxhixhixx";
Practice p=new Practice();
System.out.println(p.recur(str, 0));
}
}
This is a good opportunity to practice debugging recursive functions calls -- actually quite difficult. Suggestions:
use strategically placed print-statements to ensure that the arguments are being changed correctly from one recursive invocation to the next
refactor the order of case-analysis in the if-statement to make it more clear. For example, 1) check if the string is empty (base case), 2) check if the string starts with "hi", 3) catch-all -- not empty and doesn't start with "hi"
As #Steve mentioned, you have to use the return value that recur returns.
See below for a modified version of your code, I also simplified your if/else statements:
public int recur(String str, int counter) {
if (str.startsWith("hi")) {
return recur(str.substring(2), counter+1);
} else if (!str.isEmpty()) {
return recur(str.substring(1), counter);
} else {
System.out.println("End of text reached");
return counter;
}
}
public static void main(String args[]) {
String str = "xxhixhixx";
Practice p = new Practice();
System.out.println(p.recur(str, 0));
}
You aren't using the value returned from recur.
public int countHi(String str) {
if (str.length() <= 1) {
return 0;
}
int count = 0;
if (str.substring(0, 2).equals("hi")) {
count = 1;
}
return count + countHi(str.substring(1)); //substring off
}
All this does is recursively count the number of the String "hi" inside a larger String. The rest of the implementations should be a piece of cake, happy Coding!
Your program printing 'End of text' is correct as finally as per the logic it will reach there, reason for count always coming as 0 is that in every iteration they change there own copy and finally when the termination condition is reached(String is empty) the result is popped out of the stack, hence final outcome that you receive is the pop of the first iteration where count was 0, so you have to return the value returned by recur at every step instead of returning count.
public static int recursive(String givenStr) {
int count =0 ;
Pattern pattern = Pattern.compile("hi");
Matcher match = pattern.matcher(givenStr);
while(match.find()){
System.out.println(match);
count++;
}
return count;
}
This Will return number of times "hi" has appeared into the String

Categories