java – Binary to decimal


There are good things to point out in your solution apart from the code formatting. If you use eclipse you could press ctrl+shift+f and that will make your code more redable.


Is Binary Method

  • In Java, the values you send as parameters aren’t affected in other functions (there are some exceptions as with data structures nodes). Hence you can save the inputNumb variable
  • Make the name of your variables, methods and classes descriptive for all possible reader of your code. In the future you won’t work alone.
    public static boolean isBinary(int number) {
        while (number > 0) {
            if(number % 10 > 1)
                return false;
            number /= 10;
        }
        return true;
    }

Binary To Decimal Method

  • If a variable is declared an only used once (as lastDigit), then substitute the value assigned to it where such variable appears.
  • Make comments when needed
  • Throw exceptions when you find an inconsistency which will interfere with the correct workflow of your program
  • Don’t check twice a boolean condition, if an if else statement depends on only one condition you haven’t to check if that wasn’t true in the else block, it is redundant, an else is executed when the condition in the if fails
    public static int binaryToDecimal(int number) {
        int decimalNumber = 0;
        int powerOfTwo = 1; //renamed, gives more context
        if (isBinary(number)) {
            while (number != 0) {
                decimalNumber += (number % 10) * powerOfTwo;
                powerOfTwo *= 2;
                number /= 10; //removes the last digit
            }
        } else throw new InvalidParameterException("Not a binary number");
        return decimalNumber;
    }

The isCorrect method could be omitted since it’s used once.

    public static void main(String() args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a binary number: ");
        try {
            int binaryNumb = input.nextInt();
            int convertedNumb = binaryToDecimal(binaryNumb);
            System.out.println("The number "+ binaryNumb + " was converted to decimal," +
                    "nthe result was: " + convertedNumb);
        } catch (InputMismatchException e) {
            System.out.println("Wrong input!");
        }
    }

I wish it were of help to you.