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

In a program called DecimalToBinary.java: Write a method called convertToBinary

ID: 3728000 • Letter: I

Question

In a program called DecimalToBinary.java:

Write a method called convertToBinary that accepts an integer as a parameter and returns a String containing that integer’s binary representation.

For example. the call of convertToBinary(44) should return “101100”

Convert positive decimal number (int) to binary: http://www.wikihow.com/Convert-from-Decimal-to-Binary

main method

Include an indefinite loop that continues to prompt the user until they type -1 to quit

Include checks for invalid input (non-int or negative other than -1) and reprompts the user

Get convertToBinary working correctly before you work on the loops of the main method.

Your code should include assertion comments.

Explanation / Answer

DecimalToBinary.java

package a12;

import java.util.Scanner;

public class DecimalToBinary {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.println("Please enter decimal integer value(-1 to quit) : ");

int n = scan.nextInt();

while(n!=-1) {

System.out.println(convertToBinary(n));

System.out.println("Please enter decimal integer value(-1 to quit) : ");

n = scan.nextInt();

}

}

public static String convertToBinary(int n){

int x;

if(n > 0){

x = n % 2;

return (convertToBinary(n / 2) + "" +x);

}

return "";

}

}

Output:

Please enter decimal integer value(-1 to quit) :
44
101100
Please enter decimal integer value(-1 to quit) :
55
110111
Please enter decimal integer value(-1 to quit) :
123
1111011
Please enter decimal integer value(-1 to quit) :
-1

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote