0

Input is a decimal number and the output is supposed to be that same number in binary form in an ArrayList, but for some reason it is only outputting 1s

Digit is a class whose only value is an int "bit" and a 2-bit adder.

private ArrayList<Digit> numbers;
private Digit number;

public Converter(int val){
    numbers = new ArrayList<Digit>();
    number = new Digit(val);
    if (val == 1 || val == 0){
        numbers.add(number);
    } else{
        while (val >= 1){
            number.setValue(val % 2);
            numbers.add(number);
            val = val/2;
        }
    }
}

public String toString(){
    return "" + numbers;
}

This is outputting the correct number of elements, but all of them are 1s.

ex. 5 = 1,1,1 rather than 1,0,1.

2
  • Have you tried running it through a debugger? Note that for val = 2, this returns [0, 1]... so a zero, but its in the wrong place. Commented Feb 25, 2015 at 5:04
  • Please include the Digit class Commented Feb 25, 2015 at 5:07

1 Answer 1

1

You're using the same object of Digit to occupy all places in the ArrayList, hence it just shows the last value written to the object.

Store clone of the object in the ArrayList to get the desired result.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I didn't realize that I couldn't just change the value of the object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.