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!
8 Respuestas
+ 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
0
instead 'reference' write right return type of the method
main() should be public
public static void main(String[ ] args) {
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...
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 ?
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.
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 ?
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)
0
you return num now
you have to change it