-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 :)

2
  • 1
    Hi Juanloz... please make sure to check for similar questions before posting to Stack Overflow. Commented Dec 16, 2015 at 16:22
  • You have to always return a value, (or throw an error) You can't return a value sometimes. Commented Dec 16, 2015 at 16:32

2 Answers 2

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}
Sign up to request clarification or add additional context in comments.

1 Comment

I completed it with an else return 0; and it worked. Next time, I'll read more before asking silly questions. Thank you Spring !
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.