3
\$\begingroup\$

Can I make this code somehow faster and is this readable? I'm a beginner and in later I'll make another class with Decimal to Binary conversion, but first I've to know how to do that.

package convert.console.binaryToDecimal;
import java.util.InputMismatchException;
import java.util.Scanner;

public class ConversionProgram {
    //check if number is actually binary
    public static boolean isBin(int numb){
        int inputNumb = numb;

        while(inputNumb > 0){
            if(inputNumb % 10 > 1){
                return false;
            }
            inputNumb /= 10;
        }
        return true;
    }

    public static int binaryToDecimal(int input){

        int number = input;
        int decimalNumber = 0;
        int baseNumber = 1;
        int lastDigit;
        //check if provided number is binary
        if(isBin(number)){
            while(number != 0){

                //takes last digit from input
                lastDigit = number % 10;
                //counts decimal number
                decimalNumber += lastDigit * baseNumber;
                /*every time increase baseNumber by 2
                (base number is 1 ,because when u start from right 2pow0 is always 1)
                 */
                baseNumber *= 2;
                //removes last digit from input
                number /= 10;

            }
        }
        else if(!isBin(number)){
            System.out.println("Wrong!\nProvide binary number - contains only 0 and 1");
        }
        return decimalNumber;
    }

    //check if output is correct
    public static void isCorrect(int bin, int conv){

            if (conv == 0) {
                System.out.println("Try again");
            } else {
                System.out.println("Converted number from binary " + bin + " to decimal is " + conv);
            }
    }



    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("Input binary number :");
        try {

            int binaryNumb = input.nextInt();
            int convertedNumb = binaryToDecimal(binaryNumb);
            isCorrect(binaryNumb, convertedNumb);

        }catch(InputMismatchException e){
            System.out.println("Wrong input!");
        }
    }

}
```
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I always like to mention that a += b is not shorthand for a = a + b, but for a = (TYPE_A)(a+b). It doesn't matter in this case, but it's something to keep in mind as it might silently truncate data. \$\endgroup\$
    – Bobby
    Sep 13 '20 at 20:52
2
\$\begingroup\$

One thing, I noticed. To my mind a binary number is usually represented by a collection of digits(string,char[],byte[],etc) not an integer with only 0's and 1's. Not only would this approach be more typical it would simplify your algorithm significantly since the digits are already separated.

Another aspect to consider, an integer is restricted to the number of digits, whereas a binary number can typically have 32, 64 or even 128 bits.

\$\endgroup\$
2
  • \$\begingroup\$ So I guess ,I should use BigInteger right? While long holds only 64 bits and it'd be not enough \$\endgroup\$ Sep 13 '20 at 22:46
  • 2
    \$\begingroup\$ I would suggest using string, char and byte array overloads Instead of integers. Biginteger would work but I don't think it would have any practical value \$\endgroup\$
    – user33306
    Sep 13 '20 at 22:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.