Guest User

Untitled

a guest
Jan 19th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. import java.util.Scanner; //enable keyboard input reading
  2. public class DtoBConverter
  3. {
  4. public static void main(String args[])
  5. {
  6. Scanner sc = new Scanner(System.in); //create an instance of the Scanner class
  7. System.out.println("Enter your decimal number: "); //prompt the user about the expected input
  8. int decimal = sc.nextInt(); //read in the decimal number
  9. String binary = new String(""); //create a String to save a binary equivalent of the decimal number
  10.  
  11. while(decimal <= 0) //use a while loop to check if the decimal number is > 0
  12. {
  13. System.out.println("Your number must be > 0");
  14. System.out.println("Enter your decimal number: ");//prompt the user about the expected input
  15. decimal = sc.nextInt(); //read in the positive decimal number
  16. }
  17.  
  18. while(decimal > 0) //use a while loop to go through every digit in the decimal from right to left
  19. {
  20. binary = (decimal%2)+binary; //get the remainder after division by two and store in in the String
  21. decimal=decimal/2; //divide decimal value by two
  22. }
  23. System.out.println("The number in binary is: " + binary); //print the binary value on screen
  24. sc.close(); //close the Scanner
  25. }
  26. }
Add Comment
Please, Sign In to add comment