[SOLVED] Binary converter code refuses to work | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 4

[SOLVED] Binary converter code refuses to work

This code wont return binary, and I've looked over it numerous times and looked at people's guides and it looks written correctly but it says cannit find symbol for binary, even though binary is set. import java.util.Scanner; public class Converter { public static String toBinary(int num) { while (num>0) { String binary=""; binary=(num%2)+binary; num/=2; } return binary; } } //your code goes here 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)); } }

18th Feb 2021, 5:08 PM
Serana Zentha
Serana Zentha - avatar
6 Answers
+ 7
you should declare binary outside of while loop: public class Converter { public static String toBinary(int num) { String binary=""; while (num>0) { binary=(num%2)+binary; num/=2; } return binary; } }
18th Feb 2021, 5:13 PM
visph
visph - avatar
+ 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)); } }
22nd Mar 2021, 1:56 PM
Mailan Savelino Caberios
Mailan Savelino Caberios - avatar
+ 1
class Converter { public static int toBinary(int nums) { int x, y=0; while(nums>0) { x=(nums%2)+10^y; y++; nums = nums/2; } return nums; } } i made this logic but it is not working can somebody tell
25th Jun 2021, 7:26 PM
Sarah
Sarah - avatar
+ 1
yup as Visph said "you should declare binary outside of while loop", other than that your code is just fine. I just got done with that exercise, had the code fine... just forgot and did not realize to declare the type String in the method public static String toBinary(). Check your browser, are you using Edge, Chrome? clean cookies and all that.
29th Nov 2021, 12:14 AM
Dario Poddighe
Dario Poddighe - avatar
0
Sarah first, don't post your problem in another thread, even if less or more related: rather create your own (good redacted) thread ^^ the main problem in your code is: what do you expect 10^y will do? in most of languages, '^' is the XOR binary operator... not the power (exponentiation) operator... raising a number to a power not ever has an operator, but often has a function to compute it... search on language documentation / internet what you could use ;)
25th Jun 2021, 7:33 PM
visph
visph - avatar
0
visph thanks I'll keep that in my mind
26th Jun 2021, 10:10 AM
Sarah
Sarah - avatar