javaarraysstringjava.util.scannertype-2-dimension

In java, input text and put them into a two Dimensional character array


I am struggling to understand how to go about solving this problem. I am in need of resources to help me get a better understanding as to how to go about properly solving it or perhaps someone to explain it in another way that might help me get started. Or if someone can give me a starting point or provide an example of a code that is similar to this. I am very new at this and need it as "broke down" as possible so that I can understand all the basic fundamentals of it.

"Write a program that reads text from a file. Create a 2-dimensional character array that is 6 * 7. Store the characters read in your array in row major order (fill row 0 first, then row 1, etc.). Fill any unused spaces in the 2-D array with the ‘*’ character. If you have more characters than space, ignore the excess characters. Extract the characters from your array in column-major order (pull from column 0 first, then column 1, etc.). Build a new string as you extract the characters. Display the new string."

package programmingExercise5;

import java.util.Scanner;

public class twoDimensionalCharacterArray {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Type in a sentence: ");
        String message = scan.nextLine();
    }

}

Solution

  • Note : this will fill character space with '*' and fill the remain cell of Array 2D with '-'.

    public class twoDimensionalCharacterArray {
    
        public static void main(String[] args) {
    
            int row = 6, col = 7;
            char[][] chars = new char[row][col];
    
            Scanner scan = new Scanner(System.in);
            System.out.print("Type in a sentence: ");
            String message = scan.nextLine();
            char[] messages = message.toCharArray();
            int i = 0;
            for (int r = 0; r < chars.length; r++) {
                for (int c = 0; c < col; c++) {
                    if (i < messages.length) {
                        chars[r][c] = messages[i] == ' ' ? '*' : messages[i];
                        i++;
                    } else {
                        chars[r][c] = '-';
                    }
                }
            }
            for (char[] x : chars) {
                System.out.println(Arrays.toString(x));
            }
        }
    
    }