Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

-----------> This code needs to have the binary function handle a negative numbe

ID: 3801917 • Letter: #

Question

-----------> This code needs to have the binary function handle a negative number.

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();
   }

}

Explanation / Answer

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 Integer.toBinaryString(binaryNumber);
       }
       else
       {
           String s = "";
           do {
               s = s + (binaryNumber & 1);
               binaryNumber = binaryNumber >> 1;
           } while (binaryNumber > 0);
           return new StringBuffer(s).reverse().toString();
       }
      
   }
}