(Decimal to Binary) Write a program that prompts the user to enter a decimal integer and displays its corresponding binary value. Don’t use Java’s Integer.toBinaryString(int) in this program. Your program must have the following method.
public static String toBinary(int n)
Binary.java
/** * Decimal to Binary. */ import javax.swing.JOptionPane; // import JOptionPane public class Binary { /** Main Method */ public static void main(String[] args) { // Promt to user to enter decimal number. int decimal = Integer.parseInt(JOptionPane.showInputDialog("Please enter the decimal number:")); String binary = toBinary(decimal); // Decimal bumber convert to binary number prntStr(decimal+" in decimal system is equal to "+binary+" in binary system."); // print. } // End of main method. /** toBinary Method */ public static String toBinary(int decimal){ String result=""; int x; while(decimal>1){ // convert to binary number. x = decimal%2; decimal = decimal/2; result = x + result; } // End of while decimal>1 result = decimal + result; return result; } // End of toBinary Method. /** prntStr Method */ public static void prntStr (String s){ System.out.println(s); } // End of prnStr method. } // End of public class.
Yorum Yok:
Yorum Yap:
Yorum yapabilmek için giriş yapmalısınız.