Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
658 views
in Technique[技术] by (71.8m points)

syntax - Converting decimal to binary in Java

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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...