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

+2

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ć

9 Answers

New Answer

+4

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

+6

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

import java.util.Scanner; //your code goes here class Converter{ static String toBinary(int x){ String bin=""; while(x>0){ bin=(x%2)+bin; x/=2; } return bin; } } 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

Hi everybody. Can anyone explain, why the type of returned value in the toBinary method is String? Shouldn't it return integer? Since we are working with integers? Or am I missing something?

0

Ok. I've found kind of answer here: https://www.sololearn.com/Discuss/2923028/?ref=app But I still don't really get, why we use String to avoid exceptions with long numbers. String is, well... String. Doesn't have anything to do with numbers. ? Edit. Ok. After a long thinking, I think I understand. It's more memory efficient than using a return type long. I suppose.

0

We use string to make the binary digits visible. In memory everything is binary, even the characters in the string are encoded in 8 bits typically. But we want to see the ones and zeros so we put them in a string

-2