简体   繁体   中英

I'm trying to do a natural to binary number converter

I am a 16 year old who is trying to learn to program in Java. I set out to create this code, but I don't know if it is quite right. Why are you asking me to turn "natural" into a static? Please make any comments you can think of about the code, I try to improve my programming skills, so any comments from someone who knows a little more than I do is helpful. Thank you!

import java.util.Scanner;

public class Prueba {

    static int natural;

    public Prueba () {
        natural = 1;
    }

    public int Binario(int natural) {
        int i = 1, bin = 0;
        while(natural>0) {
            if (natural % 2 == 0)
                natural = natural / 2;
            else {
                natural = (natural-1)/2;
                bin = bin + i;
            }
            i = i*10;
        }
        return bin;
    }

    public static void main(String[] args) {
        Prueba a = new Prueba();
        Scanner in = new Scanner(System.in);
        System.out.println("Natural to binary number converter. Press 0 to stop the program");
        while (natural != 0) {
            natural = in.nextInt();
            System.out.println(a.Binario(natural));
        }
    }

}

If you want to return a binary string you can do it this way. But there are a couple of things to watch out for (covered in the comments).

Also, when you say natural number to binary I am not sure if you mean just positive numbers or decimal numbers. This method will handle both. But negative decimal numbers will not have a negative sign in binary. They will be shown in what is known as Two's Complement form. Something that you should become familiar with as you continue to learn programming.

public static String toBinary(int v) {
     StringBuilder sb = new StringBuilder();

     // since you want to handle negative numbers it's important
     // to check for not equal to 0.

     while(v != 0) {
         // insert the bit at index 0 of stringBuilder.
         // The & just masks off the low order bit and ignores
         // the others.  The result is the same as "v % 2".  But
         // I prefer bit manipulation when possible
         sb.insert(0,v&1);

         // this shifts all 32 bits right one bit and inserts a 0
         // on the left.
         v>>>=1;
     }
     return sb.toString();
}

Check the link for more on Bit Masking

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM