- 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)); } }
6 ответов
+ 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;
}
}
+ 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));
}
}
+ 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
+ 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.
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 ;)
0
visph thanks I'll keep that in my mind