Converting decimal to binary in Java

前端 未结 9 2308
时光取名叫无心
时光取名叫无心 2020-12-03 15:18

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 wit

9条回答
  •  孤城傲影
    2020-12-03 16:10

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

提交回复
热议问题