Results 1 to 2 of 2
  1. #1
    emtu is offline Member
    Join Date
    Dec 2010
    Posts
    9
    Rep Power
    0

    Default convert string to two dimensional char and output = matrix

    I have written the code:
    Java Code:
    public static void main(String[]args)
    {
        Scanner input = new Scanner(System.in);
    
        System.out.print("Type your text: ");
        String text = input.nextLine();
    
        int counter = text.length();
        if(text.length()> 16)
        {
            System.out.println("Error: input text is greater than 16 characters");
            System.exit(0);
        }
        else
        {
            while(counter < 16)
            {
                text = text.concat("x");
                counter++;
            }
    
            char[][] k = new char[4][4];
    
            int push = 0;
    
            for(int i = 0; i < k.length; i++)
            {
                for(int j = 0; j < k[i].length; j++)
                {
                    k[i][j] = text.charAt(j+ push);
                    System.out.print(k[i][j] + " ");
                }
                System.out.println();
                push = push + 4;
            }
        }
    }



    And input is: abcdefghijklm

    output is:

    Java Code:
    a b c d
    e f g h
    i j k l
    m x x x
    So all i want is, if i type: abcdefghijklm I want this output:
    Java Code:
    a e i m
    b f j x
    c g k x
    d h l x

  2. #2
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,779
    Rep Power
    5

    Default Re: convert string to two dimensional char and output = matrix

    One way is to store the characters in a 2D array. Then just change whether you iterate over columns or rows first.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Replies: 4
    Last Post: 09-26-2013, 11:35 AM
  2. Replies: 1
    Last Post: 07-27-2010, 06:01 PM
  3. Convert Char To String
    By fh84 in forum New To Java
    Replies: 15
    Last Post: 10-28-2009, 09:59 PM
  4. Convert Comparable object to string or char
    By ScKaSx in forum New To Java
    Replies: 4
    Last Post: 01-25-2009, 02:02 PM
  5. Cannot convert from char to String error
    By sondratheloser in forum New To Java
    Replies: 1
    Last Post: 12-13-2007, 09:28 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •