-1

I am working on a Game of Life java file in which I have to read in a given file with a certain number of rows containing a string of ones or zeros. (ie 0000010010100010000) How would I go about parsing the entire thing into a an integer array containing one or zero in each element?

Kick Buttowski
  • 6,631
  • 13
  • 35
  • 57

2 Answers2

1

You might want to take a look at BitSet. Java BitSet Example here is an example of using it:

import java.util.BitSet;

    class Scratch {
        public static void main(String[] args) {
            BitSet bits1 = fromString("1000001");
            BitSet bits2 = fromString("1111111");

            System.out.println(toString(bits1)); // prints 1000001
            System.out.println(toString(bits2)); // prints 1111111
            boolean nthBit = bits1.get(3);//returns 3rd bit


        }

        private static BitSet fromString(final String s) {
            return BitSet.valueOf(new long[] { Long.parseLong(s, 2) });
        }

        private static String toString(BitSet bs) {
            return Long.toString(bs.toLongArray()[0], 2);
        }
    }

This example will work only if length of your String is less than 64

Community
  • 1
  • 1
Vladislav Lezhnin
  • 777
  • 1
  • 6
  • 17
0

Code:

   String s ="0000010010100010000";
   String[] sp = s.split("");
   int[] arr = new int[sp.length];
    for (int i = 0; i < sp.length; i++) {
        arr[i] = Integer.parseInt(sp[i]);
    }

    for (int i = 0; i < arr.length; i++) {
        System.out.print(arr[i]);
    }

Explanation:

your split your string by using split function

Definition :

Splits this string around matches of the given regular expression.

public String[] split(String regex)

and parse each element of String array to int by using

public static int parseInt(String s) throws NumberFormatException

and assign it to the array of int which has same length

Kick Buttowski
  • 6,631
  • 13
  • 35
  • 57