Changing binary to decimal using created constants (not parseINT() ) and declaring and initializing each of the 8 bits of the number

Assignment

I have been working on this forever now. I am required to create Constants then declare and initiate each then multiplying each by it’s place value (128,64,32,16,8,4,2,1)

I know Integer.parseINT(Binary….) would do the job quickly however I CANNOT USE IT.

followed is what i have thus far, am i even on the right track? I know i need to get each of the separated user input values and have them multiplied by their place values then added to create the decimal but i for the life of me cannot figure out how to do it through for loop or defining each variable

import java.util.Scanner;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.lang.Integer;
import javax.swing.JComboBox;

public class Binary
{

public static void main(String [] args)
{
    Scanner keyboard = new Scanner (System.in);
    System.out.println("Enter Binary Number Please");
    Integer[] digits = getDigits(keyboard.nextInt());



    System.out.println(Arrays.toString(digits));

}//End bracket method main

    public static Integer[] getDigits(int num)
    {
        List <Integer> digits = new ArrayList <Integer>();
        collectDigits(num, digits);
        return digits.toArray(new Integer[]{});

    }//end bracket method Integer

    private static void collectDigits(int num, List <Integer> digits)
    {

       if(num / 10 > 0)
       {
            collectDigits(num / 10, digits);

        }//End method collectDigits

        digits.add(num % 10);

    }

}

I am wanting to separate each character of the user input binary so i can have them multiplied by their place value, then each product added to create the sum that will then be displayed to the user via System.out.println()

Answer

You are importing the wrong List type. Change this line:

import java.awt.List;

To:

import java.util.List;

Leave a Reply

Your email address will not be published. Required fields are marked *