开发者

Converting decimal to binary in Java

开发者 https://www.devze.com 2023-02-15 12:31 出处:网络
I\'m trying to write a code that conv开发者_如何学运维erts a number to binary, and this is what I wrote. It gives me couple of errors in Eclipse, which I don\'t understand.

I'm trying to write a code that conv开发者_如何学运维erts a number to binary, and this is what I wrote. It gives me couple of errors in Eclipse, which I don't understand. What's wrong with that? Any other suggestions? I'd like to learn and hear for any comments for fixing it. Thank you.

public class NumberConverte {
  public static void main(String[] args) {
    int i = Integer.parseInt(args);
    public static void Binary(int int1){
      System.out.println(int1 + "in binary is");
      do {
        System.out.println(i mod 2);
      } while (int1>0);
    }
  }
}

The error messages:

  1. The method parseInt(String) in the type Integer is not applicable for the arguments (String[])
  2. Multiple markers at this line
    • Syntax error on token "(", ; expected
    • Syntax error on token ")", ; expected
    • void is an invalid type for the variable Binary
  3. Multiple markers at this line
    • Syntax error on token "mod", invalid AssignmentOperator
    • Syntax error on token "mod", invalid AssignmentOperator.


Integer.toBinaryString(int) should do the trick !

And by the way, correct your syntax, if you're using Eclipse I'm sure he's complaining about a lot of error.

Working code :

public class NumberConverter {
   public static void main(String[] args) {
       int i = Integer.parseInt(args[0]);
       toBinary(i);
   }

   public static void toBinary(int int1){
       System.out.println(int1 + " in binary is");
       System.out.println(Integer.toBinaryString(int1));
   }
}


Maybe you don't want to use toBinaryString(). You said that you are learning at the moment, so you can do it yourself like this:

/*
  F:\>java A 123
  123
    1  1  0  1  1  1  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
  0  0  0  0  0  0
*/

public class A {
    public static void main(String[] args) {

        int a = Integer.parseInt(args[0]);
        System.out.println(a);

        int bit=1;
        for(int i=0; i<32; i++) {
            System.out.print("  "+(((a&bit)==0)?0:1));
            bit*=2;
        }
    }
}


I suggest you get your program to compile first in your IDE. If you are not using an IDE I suggest you get a free one. This will show you where your errors are and I suggest you correct the errors until it compiles before worring about how to improve it.


There are a two main issues you need to address:

  • Don't declare a method inside another method.
  • Your loop will never end.

For the first, people have already pointed out how to write that method. Note that normal method names in java are usually spelled with the first letter lowercase.

For the second, you're never changing the value of int1, so you'll end up printing the LSB of the input in a tight loop. Try something like:

do {
  System.out.println(int1 & 1);
  int1 = int1 >> 1;
} while (int1 > 0);

Explanation:

  • int1 & 1: that's a binary and. It "selects" the smallest bit (LSB), i.e. (a & 1) is one for odd numbers, zero for even numbers.
  • int1 >> 1: that's a right shift. It moves all the bits down one slot (>> 3 would move down 3 slots). LSB (bit 0) is discarded, bit 1 becomes LSB, bit 2 becomes bit one, etc... (a>>0) does nothing at all, leaves a intact.

Then you'll notice that you're printing the digits in the "wrong order" - it's more natural to have them printed MSB to LSB. You're outputting in reverse. To fix that, you'll probably be better off with a for loop, checking each bit from MSB to LSB.

The idea for the for loop would be to look at each of the 32 bits in the int, starting with the MSB so that they are printed left to right. Something like this

for (i=31; i>=0; i--) {
  if (int1 & (1<<i)) {
    // i-th bit is set
    System.out.print("1");
  } else {
    // i-th bit is clear
    System.out.print("0");
  }
}

1<<i is a left shift. Similar to the right shift, but in the other direction. (I haven't tested this at all.)

Once you get that to work, I suggest as a further exercise that you try doing the same thing but do not print out the leading zeroes.


For starters you've declared a method inside a method. The main method is the method that runs first when you run your class. ParseInt takes a string, whereas args is an Array of strings, so we need to take the first (0-based) index of the array.

mod is not a valid operator, the syntax you wanted was %

You can use System.out.print to print on the same line rather than println

Try these corrections and let me know how you get on:

 public class NumberConverter {
  public static void main(String[] args) {
  int i = Integer.parseInt(args[0]);
  Binary(i);
 } 

 public static void Binary(int int1){
    System.out.println(int1 + " in binary is ");
    do {
        System.out.print(int1 % 2);
        int1 /= 2;
    } while (int1 > 0);


 }
}


Here is a small bittesting code I made for Android.

int myres = bitTest(7, 128);

public int bitTest(int bit,int value)
 {
    int res = 0;
    int i = 0;
    while (i <= bit) {
        res = (value & 1);
        value = value >> 1;
        i++;
    }
    return res;
 }

Best Regards Mikael Andersson


StringBuffer sb = new StringBuffer("");
void breakNumber(int num){
    if(num == 0 || num == 1){
        System.out.println(num);
    }else{
        int modr = num % 2;
        sb.append(modr);
        int divr = num / 2;
        if(divr > 1){
              breakNumber(divr);    
        }else{
             sb.append(modr);
             StringBuffer sbr =sb.reverse();
             System.out.println(sbr.toString());    
        }
    }
 }


package gg;

import java.util.*;

public class Gg {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        boolean flag = true;
        while (flag) {
            menu();
            int n = in.nextInt();
            switch (n) {
            case 1:
                System.out.println("enter an integer decimal number : ");
                int d = in.nextInt();
                System.out.print("the answer is ");
                DTB(d);
                System.out.println();
                break;
            case 2:
                System.out.println("enter a binary number : ");
                int b = in.nextInt();
                System.out.print("the answer is " + BTD(b));
                System.out.println();
                break;
            case 3:
                flag = false;
                break;
            }
        }
    }

    public static void menu() {
        System.out.println("1.convert decimal to binary : ");
        System.out.println("2.convert binary to decimal : ");
        System.out.println("3.exit");
    }

    public static void DTB(int x) {
        int n = 0;
        int y = x;
        while (y > 0) {
            y /= 2;
            n++;
        }
        int s[] = new int[n];
        int i = 0;
        while (x > 0) {
            s[i] = x % 2;
            x /= 2;
            i++;
        }
        for (int j = s.length - 1; j >= 0; j--) {
            System.out.print(s[j]);
        }
    }

    public static int BTD(int x) {
        int y = 2;
        int sum = 0;
        double k = 1;
        int c = 0;
        while (x > 0) {
            double z = x % 10;
            x /= 10;
            k = Math.pow(y, c);
            c++;
            k *= z;
            sum += k;
        }
        return sum;
    }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消