66 843
Assignments Done
99,1%
Successfully Done
In October 2018

Answer to Question #4606 in Java | JSP | JSF for bob

Question #4606
Design and implement a class called DecToBinArray and write a test program called DecToBinArrayTest.

DecToBinArray is utility class that converts a nonnegative decimal number between 0 and 255 into an array of 0's and 1's. For example, you should be able to do the following:
DecToBinArray arr = new DecToBinArray(120);
arr.convert();
System.out.println(arr);

DecToBinArrayTest should also implement toString() method properly so that the above code snippet print out the standard output 01111000.
NOTE: that the length of the array used in DecToBinArray is always 8 since integers from 0 to 255 can be represented with 8 bits.

DecToBinArrayTest reads a string of digits representing a nonnegative integer from 0 to 255. you may read a line of text from the standard in using the following:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in))
Expert's answer

public class DecToBinArray {

private int n;



public DecToBinArray(int n){

if ((n<0) || (n>255)) throw new IllegalArgumentException("Number shold be [0;255]");

this.n = n;



}



public char[] convert(){

int size = 8;

char [] res = new char[size];

String tmp = Integer.toBinaryString(n);

int i = 0;

for(; i < tmp.length(); i++){

res[size-1-i] = tmp.charAt(tmp.length()-1-i);

}

while(i < size){

res[size-1-i] = '0';

i++;

}

return res;

}



@Override

public String toString(){

String tmp = Integer.toBinaryString(n);

while(tmp.length() != 8){

tmp = '0' + tmp;

}

return Integer.toBinaryString(n);

}

}








public class NewEmptyJUnitTest {



public void test() {

Scanner keyboard = new Scanner(System.in);

System.out.print("Input value: ");

int c = keyboard.nextInt();

DecToBinArray ar = new DecToBinArray(c);

if(Integer.toBinaryString(c).equals(ar.toString())){

System.out.print("Test passed");

} else {

System.out.print("Test failed");

}

}

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions