0

Error in java code

Hi all, In one exercise I got java errors that I can't fix. My code is the following: import java.util.Scanner; class Converter { static reference toBinary(int num) { String binary = ""; while (num>0) { binary = (num%2)+binary; num /=2; } return num; } static reference main(String[ ] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); { System.out.println(Converter.toBinary(num)); } } } Could you please help me to understand how I can fix my code. Thanks in advance!

12th Nov 2021, 4:43 PM
Дарья Боринских
8 Réponses
+ 3
Your main function static reference main it should be public static void main i think then after class name your reference to Binary this line giving error
12th Nov 2021, 5:03 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
0
instead 'reference' write right return type of the method main() should be public public static void main(String[ ] args) {
12th Nov 2021, 5:05 PM
zemiak
0
Hi, Thank you for your comments. Updated my code like this: import java.util.Scanner; class Converter { static int toBinary(int num) { String binary=""; while (num>0) { binary = (num%2)+binary; num /=2; } return num; } public static void main(String[ ] args) { Scanner sc = new Scanner(System.in); int num = sc.nextInt(); { System.out.println(Converter.toBinary(num)); } } However, it gives result 0 and not expected binary numbers. Looks like there is some other error...
12th Nov 2021, 9:40 PM
Дарья Боринских
0
temporarly add some control output in while while (num>0) { binary = (num%2)+binary; num /=2; System.out.println( "num= " +num +", binary= " +binary); } you are returning num, what is num at end of loops ? what you really want to return ?
12th Nov 2021, 11:42 PM
zemiak
0
I use num as input for the program that converts numbers into binary numbers, this is one of code projects here in this app. Currently it returns 0, not sure why, looks like there is an error in math part, not in syntax.
15th Nov 2021, 10:08 AM
Дарья Боринских
0
math logic is correct while (num>0) { binary = (num%2)+binary; num /=2; if you repeatedly divide a number, finally you get something near to zero int type cut decimal part so you get 0 it is OK, but then why you try return zero where is building your binary result ?
15th Nov 2021, 11:38 AM
zemiak
0
No, I am not trying to return zero. I expect to get binary numbers in results, but it returns 0 instead. That's why I assume that there is some error, my code doesn't return expected values (like 1111 or 01110 or 0001)
16th Nov 2021, 3:34 PM
Дарья Боринских
0
you return num now you have to change it
16th Nov 2021, 4:18 PM
zemiak