Advertisement
madegoff

Dec2Bin java

May 11th, 2024
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. import java.util.Stack;
  2. /** * A class for constructing a Decimal-to-Binary Number- Converter; * contains a main method for demonstration. */
  3. public class Dec2Bin {
  4.  
  5. public Stack<Integer> binStack; // We make it public to modify it in our tests.
  6. private int N;
  7.  
  8. /**
  9. * Constructor of an empty object. Use method {@code convert()} to convert a number.
  10. */
  11. public Dec2Bin() {
  12. binStack = new Stack<>();
  13. }
  14.  
  15. /**
  16. * Returns the number that is converted as {@code int}.
  17. *
  18. * @return the converted number
  19. */
  20. public int getN() {
  21. return N;
  22. }
  23.  
  24. /**
  25. * Converts the given number into binary format, with each digit being represented in a
  26. * stack of {@code int}.
  27. *
  28. * @param N the number that is to be converted.
  29. */
  30. public void convert(int N) {
  31. // TODO implement this method
  32. int bin;
  33. while(N!=0){
  34. bin = N%2; // 1 oder 0, Rest von Division durch 2, anafangen mit niedrigstem Wert
  35. N = N/2;
  36. binStack.push(bin);
  37. }
  38. }
  39.  
  40. /**
  41. * Returns the digits that are stored in {@code binStack} as a string. To is the binary format of the
  42. * converted number.
  43. * For testing purpose, we require that the function works also, if the variable {@code binStack} is
  44. * modified externally.
  45. *
  46. * @return a string representation of the number in binary format.
  47. */
  48. @Override
  49. public String toString() {
  50. // Caution: Stack.toString() does NOT respect stack order. Do not use it.
  51. // TODO implement this method
  52.  
  53. // Kopie des Stacks erstellen
  54. Stack<Integer> copyStack = new Stack<>();
  55. copyStack.addAll(binStack);
  56.  
  57. int size = binStack.size(); //wie viele Elemente vorhanden fuer Iterierung
  58. String res_str = new String(); //wo wir rueckgabestring lagern
  59.  
  60. for (int i = 0; i < size; i++) {
  61. int bin = copyStack.pop(); //leeren die kopie von unserem stack
  62. res_str+=bin;
  63. }
  64. return res_str;
  65. }
  66.  
  67. public static void main(String[] args) {
  68. Dec2Bin dec2bin = new Dec2Bin();
  69. dec2bin.convert(50);
  70. System.out.println("Die Zahl " + dec2bin.getN() + " in Binärdarstellung: " + dec2bin);
  71. // Do it another time to demonstrate that toString does not erase the binStack.
  72. System.out.println("Die Zahl " + dec2bin.getN() + " in Binärdarstellung: " + dec2bin);
  73. }
  74. }
  75.  
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement