I\'m trying to make a program that prints out binary number if you put numbers.
ID: 3543260 • Letter: I
Question
I'm trying to make a program that prints out binary number if you put numbers. The requirement is that I can use a limited # of methods since I've learned a little so far.. I cannot use higher level codes. Anyway,, the problem is I need to change the remainder of number into string and add them up as one string to represent binery number. But s = remainder + s; <<< this one gives me an error.. Please help me out.. I believe this is the last step...
import java.util.Scanner;
public class BinaryRep {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a number");
int number = input.nextInt();
String s;
while (number != 0 ) {
int remainder = number % 2;
s = remainder + s;
number /= 2;
System.out.println(number);
System.out.println(remainder);
System.out.println("string is " + s);
}
}
}
Explanation / Answer
you will have to initialize the string s,then only u can add (concatenate).So, i have
initialized the string with nothing.(see bold line in code).now it will work.
***************************************program************************************
import java.util.*;
public class BinaryRep {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a number");
int number = input.nextInt();
String s="";
while (number != 0 ) {
int remainder = number % 2;
s = remainder + s;
number /= 2;
System.out.println(number);
System.out.println(remainder);
System.out.println("string is " + s);
}
}
}