Why does return statement return's default value

49 views Asked by At

I try to check the user input which should be either 0 or 1.the program returns true if it is 1 and return false if it is 0 and if any other integer values except(1 and 0) it again call itself to get the correct input.

It works fine with 1 or 0 at first time but if I try to provide other number at first time the method will called and get the input but It returns the false even I provide 1 or 0.

//this is the code...

import java.util.Scanner;

class Calculator{

    public static boolean choice;
    public static Scanner input;
    public static void main(String[] args) {
        choice = getChoice();
        //System.out.println("after choice");
        if(choice) System.out.println("true");
        else System.out.println("false");
    }
    public  static boolean getChoice() {
        input = new Scanner(System.in);
        System.out.println("1 : Start Calculator ");
        System.out.println("0 : Exit ");
        int number = input.nextInt();
        if (number == 1) return true;
        else if (number == 0) return false;
        else {
            System.out.println("Choose either 1 or 0 ");
            getChoice();
        }
        //System.out.println("before return");
        return false;
    }
}
2

There are 2 answers

0
Stultuske On
  if (number == 1) return true;
    else if (number == 0) return false;
    else {
        System.out.println("Choose either 1 or 0 ");
        getChoice(); // you don't do anything with the result of this method
    }
    //System.out.println("before return");
    return false; // this is hardcoded to happen, unless the original input was either 0 or 1

modify this to:

switch (number) {
  case 1: return true;
  case 0: return false;
  default: return getChoice();
}
// don't hardcode return false
0
Mio On

because you're literally returning false if the number is not 1 or 0. you're not returning the the value of getChoice(). the last return statement should return getChoice()

  if (number == 1) return true;
else if (number == 0) return false;
else {
    System.out.println("Choose either 1 or 0 ");
    return getChoice();
}
//System.out.println("before return");