1

I'm stumped as to why this code is throwing a fit over not having a return statement when I do have one included. Any help would be appreciated!

Code in question:

   public static int getSize()
   {
      Scanner kbd = new Scanner(System.in);
      int x = 1;
      while(x==1){
         System.out.println("Enter the size (>0): ");
         int n = kbd.nextInt();
         if (n>0){
            x--;
            return n;
         }
      }
   }
Pointy
  • 405,095
  • 59
  • 585
  • 614
MooTorial
  • 45
  • 1
  • 5

4 Answers4

4

You get the error because not all of the code paths return a value.

Add this line: return 0; at the end of the method:

public static int getSize()
{
     Scanner kbd = new Scanner(System.in);
     int x = 1;
     while(x==1){
         System.out.println("Enter the size (>0): ");
         int n = kbd.nextInt();
         if (n>0){
            x--;
            return n;
         }
     }

      return 0; // Add this line
}

Suppose that n <= 0. Then the existing return statement will never be called, hence the method will never return. So you need to assure to the compiler that the method will return a default value no matter what, by adding return 0.

Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
1

There's a return in the loop, but the compiler isn't certain that the loop won't exit without hitting that statement. Because it thinks the end of the function might be reached, it gives that error.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

Your code will not reach the return statement in all cases. You will need to add a default return statement outside your loop.

ewanc
  • 1,284
  • 1
  • 12
  • 23
0

Because you are no covering all the possibles ways in your code, I mean, if n>0 is false, the method will never return anything

try this

   public static int getSize()
   {
      Scanner kbd = new Scanner(System.in);
      int x = 1;
      while(x==1){
         System.out.println("Enter the size (>0): ");
         int n = kbd.nextInt();
         if (n>0){
            x--;
            return n;
         }
      }

      // Bad response 
      return -1;
   }
Francisco Hernandez
  • 2,378
  • 14
  • 18