Binary Converter Java | Sololearn: Learn to code for FREE!

0

Binary Converter Java

So i have a problem with finishing this project this is how I did my code: import java.util.Scanner; //your code goes here public class Converter { public static toBinary(int num) { String binary="" ; while(num > 0){ binary = (num%2)+binary; num/=2; } return binary; } } public class Program{ public static void main(String[ ] args) { Scanner sc= new Scanner(System.in); int x=scr.nextIn(); System.out.println (Converter.toBinary(x)); } } But I don't get any output with this code! Would appreciate any advice, thank you in advance!

1/14/2021 6:00:26 PM

Lara Mijanović

5 Answers

New Answer

+3

You have some typos and return type is missing. Return type is String and the typos i spotted are on reading input so the line should be: int x = sc.nextInt();

+3

public class Converter { public static String toBinary(int num) { return Integer.toBinaryString(num); } } See: https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Integer.html#toBinaryString(int)

+3

import java.util.Scanner; public class Converter { public static String toBinary(int num) { String binary=""; while(num > 0) { binary = (num%2)+binary; num /= 2; } return binary; } } public class Program { public static void main(String[ ] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); System.out.print(Converter.toBinary(x)); } }

0

Thank you! Now it works!

0