Java: Create a function called binary that will take a decimal number (can assum
ID: 3862995 • Letter: J
Question
Java:
Create a function called binary that will take a decimal number (can assume short int) and return a string of binary digits. Since it is short int, the largest string of digits would be about 16 – assume the number is positive.
Have the main program input the numbers, check to make sure the number is not not negative. If they are print an error message. Otherwise call the binary function and print the answer.
For this, you may have just one file with main and the function together.
********************have the binary function handle a negative number.
Explanation / Answer
BinaryTest.java
import java.util.Scanner;
public class BinaryTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a deciaml number: ");
int binaryNumber = scan.nextInt();
System.out.println("Binary String is "+binary(binaryNumber));
}
public static String binary(int binaryNumber){
if(binaryNumber<=0){
return "Invalid Input. Input must be greather than 0.";
}
String s = "";
do {
s = s + (binaryNumber & 1);
binaryNumber = binaryNumber >> 1;
} while (binaryNumber > 0);
return new StringBuffer(s).reverse().toString();
}
}
Output:
Enter a deciaml number:
88
Binary String is 1011000
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.