Home > OS >  How to fill 2D array using input (scanner method) without spaces
How to fill 2D array using input (scanner method) without spaces

Time:06-01

I need to fill 2D array using input without spaces, so for this I'm trying to use 'String' firstly.

import java.util.Scanner;
import java.util.Arrays;


public class TikTakToe {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    
    char[][] TikTakToe = new char[3][3];
    System.out.print("Enter cells: ");
    String enter = scanner.next();
    for (int i = 0; i < TikTakToe.length; i  ) {
        for (int j = 0, l = 0; j < TikTakToe[i].length && l < enter.length(); j  , l  ) {
            TikTakToe[i][j] = enter.charAt(l);
        }
    }
    
    for (char[] chars : TikTakToe) {
        System.out.println(Arrays.toString(chars).substring(1).replaceFirst("]", 
        "").replace(", ", " "));
    }
}

}

Input: XOXOXOXOX
Output: 
X O X
X O X
X O X

The problem in this solving that variable 'l' resets after outer 'for' loop goes to the next stage. How can I fix it?

CodePudding user response:

You're problem is that you defined the variable l in the nested for loop. Consequently, when that loop returns, l is deleted.

What you would need to do is define l before the first loop, that way its scope is the whole method.

...
char[][] TikTakToe = new char[3][3];
System.out.print("Enter cells: ");
String enter = scanner.next();
int l = 0; // <-- **I moved the declaration here**
for (int i = 0; i < TikTakToe.length; i  ) {
    for (int j = 0 /*removed the declaration from here*/; j < TikTakToe[i].length && l < enter.length(); j  , l  ) {
        TikTakToe[i][j] = enter.charAt(l);
    }
}
...

CodePudding user response:

You should initialize int l = 0 outside the loop. As it will be re-initialized when inner loop will run.

So your final code would look like :-

import java.util.Scanner;
import java.util.Arrays;


public class TikTakToe {
    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    
    char[][] TikTakToe = new char[3][3];
    System.out.print("Enter cells: ");
    String enter = scanner.next();

    int l = 0;                    // initialize here

    for (int i = 0; i < TikTakToe.length; i  ) {
        for (int j = 0; j < TikTakToe[i].length && l < enter.length(); j  , l  ) {
            TikTakToe[i][j] = enter.charAt(l);
        }
    }
    
    for (char[] chars : TikTakToe) {
        System.out.println(Arrays.toString(chars).substring(1).replaceFirst("]", 
        "").replace(", ", " "));
    }
}
  • Related