9

I'm trying to write a code that converts 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.
user207421
  • 305,947
  • 44
  • 307
  • 483
Unknown user
  • 44,551
  • 16
  • 38
  • 42
  • 2
    can you write what your input was and also what the error was, always helps speed things up – TimCodes.NET Mar 05 '11 at 13:08
  • thank you for the comment. certainly, 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. – Unknown user Mar 05 '11 at 13:11
  • The next time, add the error messages directly to the question (there is an edit link there). I did this for you now. – Paŭlo Ebermann Mar 05 '11 at 17:39
  • There is no decimal here. The input is already binary. – user207421 Apr 06 '17 at 23:48

8 Answers8

17

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));
   }
}
Luke Woodward
  • 63,336
  • 16
  • 89
  • 104
krtek
  • 26,334
  • 5
  • 56
  • 84
7

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;
        }
    }
}
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Bernd Elkemann
  • 23,242
  • 4
  • 37
  • 66
1

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

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);


 }
}
TimCodes.NET
  • 4,601
  • 1
  • 25
  • 36
  • Thank you chimoo for the comment! 1. Why do I have to put the [0] in the parseInt function? 2.Can I use "mod" Instead of &? 3.And now, after there's no syntax errors, it still says Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at NumberConverte.main(NumberConverte.java:4). How can I start my code? How do I input a string? – Unknown user Mar 05 '11 at 13:28
  • 1. the [0] is an index into the array (a collection of strings) 0 is the first 2. you can't use mod 3. you input a string by saying `java NumberConverte 32` – TimCodes.NET Mar 05 '11 at 13:59
  • where do i write that? I want to have the input from a user, is this for that? – Unknown user Mar 05 '11 at 14:13
  • yes in the console, except i forgot your using eclipse, i don't know about eclipse, sorry. you mmight want to note the code for your binary method is wrong too, see other answers – TimCodes.NET Mar 05 '11 at 14:16
1

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
0
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());    
        }
    }
 }
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

-1
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;
    }

}
Dan-Dev
  • 8,957
  • 3
  • 38
  • 55