0

I have written my program to get input from the user in the form of a string consisting of 8 numbers. I want to split the 8 numbers so I can access each of them individually. Is it kind of the same as Python where I'd use input[1] or so to access them, also how do I split them?

I'm not sure what way to go about it.

Scanner sc = new Scanner(System.in);
String input;
System.out.println("Please type your number in 8 bit binary form: ");
input = sc.nextLine();

The code runs fine so far, just don't know how to split the input into an array of 8 different numbers.

Tom
  • 16,842
  • 17
  • 45
  • 54
  • 4
    Possible duplicate of [How to split a string in Java](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – pringi Oct 02 '19 at 14:15
  • 2
    8 numbers (`10 20 30 4 55 6 777 8888`) or 8 digits (`12435687`)? – user85421 Oct 02 '19 at 14:24
  • @CarlosHeuberger The code says "8 bit binary form", so something like "10010010". – Tom Oct 02 '19 at 14:31
  • @Tom title and text says "8 numbers" so something like `"10 20 30 4 55 6 777 8888"` - I think it is wise to ask **OP** for what is really meant and not just guess something – user85421 Oct 02 '19 at 14:44

3 Answers3

0

You could try something as simple as that!

for (char vl:input.toCharArray()){
  System.out.println(vl);
}

The question is what are your split restrictions.

Michael Michailidis
  • 1,002
  • 1
  • 8
  • 21
0

You can use charAt() function to get values sequentially for all characters in the string.

Alternatively, you can do something like this:

String[] array = input.split(""); //split your string into string array using regex to define delimiter
    ArrayList<Integer> numbers = new ArrayList<>(); //initialize array of numbers
    for (String s: array) {
        numbers.add(Integer.parseInt(s)); // parse each string as Integer value
    }

So u will have numbers array, then you can access each number by it's index.

0

Why not do this

String[] binaryArray = input.split("");
Martin'sRun
  • 522
  • 3
  • 11