-1
import java.util.Scanner;

public class Main {

public static String doStuff(int num){
    //your code here
    for(int i = 1; i < 5; i++){
        if(i == num){
            String str = String.valueOf(i);
            return str;
        }
        else if(i > 4){
            return "too large";

        }
        else if(i < 1){
            return "too small";
        }
    }

}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    int n = in.nextInt();
    for(int i=0; i<n; i++){
        int a = in.nextInt();
        System.out.println( doStuff(a) );
    }
}

}

When I run this code, I get the following error:

Main.java:21: error: missing return statement
}
^
1 error

How should i do to solve this problem ?

see the below condition: Given a number from 1 to 4 (inclusive), return a word representation of the number. For example, given 2, return two. If the number is greater than 4, return the phrase too large. If the number is less than 1, return the phrase too small.

Harmlezz
  • 7,972
  • 27
  • 35
Bill
  • 9

2 Answers2

4

All the return statements in doStuff() method are conditional return statements(present either inside if-else or the for loop). You need to have a default return at the end of the method, so that the method returns something in case none of the conditional blocks are executed.

public static String doStuff(int num){
    //your code here
    for(int i = 1; i < 5; i++){
        if(i == num){
            String str = String.valueOf(i);
            return str;
        }
        else if(i > 4){
            return "too large";

        }
        else if(i < 1){
            return "too small";
        }
    }
    return null; // default return in case none of the if-else blocks are executed.
}
Rahul
  • 44,383
  • 11
  • 84
  • 103
0

You are returning values within for loop. You should return some default value.

public static String doStuff(int num){
    //your code here
    for(int i = 1; i < 5; i++){
        if(i == num){
            String str = String.valueOf(i);
            return str;
        }
        else if(i > 4){
            return "too large";

        }
        else if(i < 1){
            return "too small";
        }
    }
    return "default";
}
Suhas K
  • 74
  • 8