-3

I've been learning Java for two weeks and I'm stuck on this exercise. This might be a very simple question but I couldn't find the problem yet. I'm trying to test the first method I've written in this algorithme :

 1 import java.util.*;
 2 public class stationnement {
 3                  public static void main (String[] args) {
 4                  int j = jour();
 5                  System.out.println(j);
 6         }
 7         public static int jour() {
 8                 Scanner sc = new Scanner(System.in);
 9                 System.out.println("Rentrez le jour");
10                 int x = sc.nextInt(); 
11                 if (x > 0 && x <=31){return x;}
12         }       
13         
14 }       

When I compile my code I get stationnement.java:12: error: missing return statement }, even though I put the return x after the condition. I tried deleting the if condition and it worked. But I would like to know what's the problem here. Isn't correct to place the condition there?

Thanks a lot for your help :)

Juanloz
  • 17
  • 1
  • 5

2 Answers2

0

your method public static int jour() ...... expects a return statement

your are returning the value on the if part if (x > 0 && x <=31){return x;}

you should also return a value when if condition fails

change your code something like the below

 if (x > 0 && x <=31){return x;}
else{return 0;// I am returning 0 when if condtion fails}
SpringLearner
  • 13,738
  • 20
  • 78
  • 116
  • I completed it with an else return 0; and it worked. Next time, I'll read more before asking silly questions. Thank you Spring ! – Juanloz Dec 16 '15 at 16:34
0

The return statement you have provided is inside the if block which means the return statement wouldn't be executed or reached if the condition is false. You must provide a return statement outside the if statement which will be used even if the condition is false.The function must return something since its not void.But in this case,it doesn't if the condition is not satisfied.You will have to use an 'else' block and return 0.

Mathews Mathai
  • 1,707
  • 13
  • 31