Reputation: 27
Having a problem converting loop output into an array. I am converting a decimal into binary form but I want it to print out from left to right rather than in a vertical line. I assume there is a way to add the loop output into an array 1 by 1. My code snipet from the program:
if (choice == 2)//convert decimal to binary
{
System.out.println("Enter a decimal digit between -512 and 511 to convert to binary.");
decimal = keyboard.nextInt();
decimal2 = decimal;
while(decimal > 0){
decimal2 = decimal % 2;
decimal = decimal /2;
System.out.println(decimal2);
}
}
Thanks for any help!
Upvotes: 0
Views: 106
Reputation: 311
You can use a string to concatenate the remainder values.
String ans="";
inside the loop
decimal2 = decimal % 2;
decimal = decimal /2;
ans = decimal1+ans;
outside the loop you print:
System.out.println(ans);
Upvotes: 1
Reputation: 31637
Use Java conventions while writing Java programs...
if (choice == 2)//convert decimal to binary {
System.out.println("Enter a decimal digit between -512 and 511 to convert to binary.");
decimal = keyboard.nextInt();
System.out.print("Binary number is ");
while(decimal > 0) {
System.out.print(decimal % 2);
decimal = decimal / 2;
}
}
Note:
If you don't need to write like above, you can use below too
System.out.println("Binary of number is : " + Integer.toBinaryString(keyboard.nextInt()));
Upvotes: 0
Reputation: 61512
Whenever possible you should use the built-in Java methods, because they are generally more reliable than anything you write:
You can use Integer.toBinaryString()
to easily convert to from decimal to binary:
example:
//read from STDIN
decimal = keyboard.nextInt();
//Converts decimal to a binary representation in String format
String bitString = Integer.toBinaryString(decimal);
//print result to STDOUT
System.out.println(bitString);
Note: another advantage to doing it this way is all of the digits of the binary number are side by side. Which I believe was your original goal.
Upvotes: 0
Reputation: 13097
You can just use System.out.print(decimal2)
instead of println()
, which inserts the newline character.
Upvotes: 0