3

Currently, I just have data store the length of the bits, which isn't what I'm looking for.I would like to store the bits generated by the BinaryNumber constructor into the attribute private int data[]. data would later be used for other methods (for retrieving bit length,conversion to decimal, etc.). I am pretty new to Java programming, so I would very much appreciate if you can help me with this problem that I am facing.

public class BinaryNumber {

    private int data[]; 
    private boolean overflow; 



    /**
     * Creates a binary number of length length 
     * and consisting only of zeros.
     * 
     * @param Length
     * 
     **/

    public BinaryNumber(int length){
        String binaryNum=" "; 
        for (int i=0; i<length;i++) {
            binaryNum += "0";

        }
        System.out.println(binaryNum);
        data= new int[length];
    }



public static void main (String[] args) { 
        BinaryNumber t1=new BinaryNumber(7);

        System.out.println(t1);
    }

For example, the test above should generate seven 0s (0000000) and I would like to store those seven bits into the array data instead of what I do in my current code, which is storing it into a String binaryNum.

4
  • 2
    It's unclear what you're asking. Show sample input and output. Commented Sep 9, 2016 at 23:19
  • @shmosel edited the description for more clarity. Commented Sep 9, 2016 at 23:27
  • You mean like data[i] = 0? Commented Sep 9, 2016 at 23:28
  • @shmosel yes! Thank you. Commented Sep 9, 2016 at 23:40

1 Answer 1

2
public BinaryNumber(int length) {
    data = new int[length];
    for (int i = 0; i < length; i++) {
        data[i] = 0;
    }
}

The Java spec, however, guarantees that all int values are initialized with 0, so your constructor could be simplified to just:

public BinaryNumber(int length) {
    data = new int[length];
}
Sign up to request clarification or add additional context in comments.

1 Comment

To be exact, all array elements (the case here) and also method fields are initialized: number and char to 0, boolean to false, reference to null. But local variables of any type (int or other) are not initialized unless you write an initializer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.