简体   繁体   中英

Filling a 2D Array with user input (integer to binary)

I have to take a user input of integers from a range, convert that to binary, and fill a 3x3 array with the binary. The only problem is, my code is giving me an output of only dependent on the first 3 numbers of that binary (ie 010001101 = 010 across all rows).

import java.util.Scanner;
public class HW11P02 { 

    public static void main(String[] args) {
        Scanner in = new Scanner (System.in);
        System.out.print("Enter a number between 0 and 511: ");
        int n = in.nextInt();


        String binary = Integer.toBinaryString(n);
        binary = binary.format("%09d", Integer.parseInt(binary));
        System.out.println(binary);

        listArray(binary);


    };

    public static String[][] listArray(String binary) {
        String[][] array = new String[3][3];

        char ch = ' ';
        String value = "";

        for (int i = 0; i < 3; i++) {
            for (int n = 0; n < 3; n++) {
                ch = binary.charAt(n);
                value = Character.toString(ch);
                array[i][n] = value;
                System.out.print(array[i][n] + " ");
            }
            System.out.println();
        }



        return array;
    }
};

I think this will provide the the output you may really want.

import java.util.Scanner;

public class HW11P02 {

public static void main(String[] args)
{
    Scanner in = new Scanner (System.in);
    System.out.print("Enter a number between 0 and 511: ");
    int n = in.nextInt();

    String binary = Integer.toBinaryString(n);
    binary = binary.format("%09d", Integer.parseInt(binary));
    System.out.println(binary);

    int result[][]=new int[3][3];
    int position=0;
    for (int i = 0; i < result.length; i++)
    {
        for (int j = 0; j < result.length; j++)
        {
            result[i][j]=binary.charAt(position++)-'0';
            System.out.print(result[i][j]+" ");
        }
        System.out.println();
    }


}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM