Advertisement
Guest User

binay_to_decimal_code

a guest
Apr 27th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. import javax.swing.JOptionPane;
  2. public class New_Binary
  3. {
  4.  
  5.  
  6. public static void main(String[] args)
  7. { // TODO Auto-generated method stub
  8. String input;
  9. int num;
  10.  
  11. Object convertOptions [] = {"Decimal to Binary", "Binary to Decimal", "Decimal or Binary to Octaldecimal", "Decimal or Binary to Hexadecimal"};
  12. final Object choice = (Object) JOptionPane.showOptionDialog(null, "What would you like to convert to?", null, JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, convertOptions, null);
  13.  
  14.  
  15. if (choice.equals(0))
  16. {
  17. input = JOptionPane.showInputDialog("Enter a decimal number: ");
  18. System.out.println(input);
  19. num = Integer.parseInt(input);
  20.  
  21. System.out.println("Answer: ");
  22.  
  23. while (num > 0)
  24. {
  25. int binary = 0;
  26. int remainder = num % 2;
  27.  
  28.  
  29. binary = remainder + binary;
  30. num = num / 2;
  31. System.out.print(binary);
  32. }
  33. num++;
  34.  
  35. }
  36.  
  37.  
  38. if (choice.equals(1))
  39. {
  40.  
  41. input = JOptionPane.showInputDialog("Enter a binary number: ");
  42. System.out.println(input);
  43. num = Integer.parseInt(input);
  44.  
  45.  
  46. int decimal = 0;
  47. int power = 0;
  48.  
  49. while(num > 0)
  50. {
  51. int remainder = num % 10;
  52. decimal += (remainder*Math.pow(2, power));
  53.  
  54. num= num/10;
  55. power++;
  56. }
  57.  
  58. System.out.println("Answer:" + decimal);
  59.  
  60. }
  61.  
  62. if (choice.equals(2))
  63. {
  64.  
  65. }
  66.  
  67.  
  68. if (choice.equals(3))
  69. {
  70. input = JOptionPane.showInputDialog("Enter a decimal number: ");
  71. System.out.println(input);
  72. num = Integer.parseInt(input);
  73.  
  74. char hex [] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
  75.  
  76. String answer = " ";
  77.  
  78. while(num > 0)
  79. {
  80. int remainder = 0;
  81. remainder = num % 16;
  82. answer = hex [remainder] + answer;
  83. num = num / 16;
  84. }
  85.  
  86. System.out.print("Answer: ");
  87. System.out.print(answer);
  88. }
  89.  
  90.  
  91.  
  92. }
  93.  
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement