Aaron Hansen Aaron Hansen -5 years ago 157
Java Question

Integers from a String to an Int array

I'm writing a simple tic tac toe game and need to accept user input during their turn. The player should simply provide a set of coordinates for where to place their token (1,1) to (3,3). I am supposed to be able to accept input as either "2 1" or "2,1" or "2, 1". So I need to be able to take their String input and pull out each of the two numbers, regardless of delimiter and use them to assign their token to the specified cell in the 3x3 array.

The major catch is only being able to utilize stuff we've been taught already (this is the first quarter of Java). This is the first seven chapters of Building Java Programs which consists of Scanner, conditionals/logic, loops and arrays. No patterns, matchers, lists, etc.

Is there a way to accomplish this using only the String class, scanner, or arrays?

Answer Source

Just using the String class, you can use String.split() to get an array of strings which can then be parsed to Integers

public class Example{

 public static void main(String []args){
     String str = "2 1";
     // first split the original string on a comma
     String[] str_arr = str.split(",");
     // if the length is one then there were no commas in the input, so split again on white space
     if (str_arr.length == 1){
         str_arr = str.split(" ");
     int[] int_arr = new int[str_arr.length];
     // assign the string array to an int array
     for (int i = 0; i < str_arr.length; i++){
         int_arr[i] = Integer.parseInt(str_arr[i]);
    // output to console         
     for (int j : int_arr){

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download