Hi folks!

I need some homework help. I have the following requirements:

// Strings required for Homework.
String[]strVector = {"octhkeugrk", "fedjigchba", "mnpqdetjhz",
"bgxlvfcdaz"};
a) Write code that transforms the string array provided above into a 2 dimensional
character matrix, (e.g., char[][] charMatrix;).
b) Once in the two dimensional array form, use insertion sort to sort the characters of
each row, from a-z.
c) Create your own CharacterLinkedList class, where each node in the list will hold
a single character.
d) Create an array of 4 elements of type CharacterLinkedList.
e) Use the sorted 2D array from step (b), and for each row of the 2D charMatrix,
create a new CharacterLinkedList object and save this object in a cell of the array
created in step (d). For each row in the 2D charMatrix, push back each character
to the back of the associated linked list, as seen below.

My output should look like this:

Welcome to Homework #4
1. Execute Problem 4.2
2. Exit
Enter Option: 43
Invalid option! Please try again!
Welcome to Homework #4
1. Execute Problem 4.2
2. Exit
Enter Option: 1
->List 1: c, e, g, h, k, k, o, r, t, u
->List 2: ...
->List 3: ...
->List 4: ...
Welcome to Homework #4
1. Execute Problem 4.2
2. Exit
Enter Option: 2
Good Bye!

I've created the code for the menu, which operates smoothly and meets all the requirements listed. I've also created a class for the string array to char matrix and that prints just fine. When I've attempted to sort it using Arrays.sort, things got messy. I was able to have it print an output, but I lost the formatting so I tried something different, and now it throws exception errors. I've also set up a linkedlist class, but I have no clue how to tie the results of sort to the nodes and output it. Can any one help? Maybe point me to valid options or perhaps some pseudocode to get my brain moving toward a completed resolution.

Here is the code:

import java.util.Scanner;
public class HomeworkFourDriver 
{

        //variable to store user's choice
        static int userSelection = 0;  
        //necessary scanner to take choice from user
        static Scanner input = new Scanner(System.in);

        //Print out of menu for user to make choice
        public static void mainMenu()
        {
            System.out.println("Welcome to Homework #4.");  
            System.out.println("1. Execute Problem 4.2");
            System.out.println("2. Exit \n ");
            System.out.print("Make your selection: ");

        }
        //exit method
        public static void exit()
        {
            System.out.println("You are exiting the program. Good Bye!");
        }

        //main with loop to return to main menu after program executes
public static void main(String[] args) 
        { 

            do
            {
                mainMenu();
                //gets variable from scanner 
                userSelection = input.nextInt();

                //program chooses method based on user input
                switch(userSelection)
                {
                //if user chooses option 1, calls method for problem 3.2    
                case 1:
                    MatrixSort myMatrixSort =  new MatrixSort();
                    myMatrixSort.getMatrix();
                    break;
                //if user chooses option 3, program exits   
                case 2:
                    exit();
                    break;
                //if user selects any other option - handles error  
                default:
                    System.out.println("\nInvalid option! Please try again! \n");
                }
                //loop continues until option exit option is used
            } while(userSelection != 2);

        }

}

and the matrix:

import java.util.Arrays;


public class MatrixInsert 
{
    public static void main(String arg[])
    {
        //String required for homework
        String[] strVector = {"octhkeugrk", "fedjigchba", "mnpqdetjhz", "bgxlvfcdaz"};

        //Create matrix
        char[][] charMatrix = new char[4][10];
        for (int x = 0; x < strVector.length; x++) //set size based on the strVector array
            charMatrix[x] = strVector[x].toCharArray(); //convert to array
        Arrays.sort(charMatrix);

        for(int x=0;x<4;x++) //define rows
        {
            for(int y=0;y<10;y++) //define matrix columns
            {
                System.out.print(charMatrix[x][y]+" "); //to screen
            }
                System.out.println();
        }
    }
}

and finally, what I have so far for the linkedlist:

public class LinkedList
{
    // reference to the head node.
    private Node head;
    private int listCount;

    // LinkedList constructor
    public LinkedList()
    {
        // this is an empty list, so the reference to the head node
        // is set to a new node with no data
        head = new Node(null);
        listCount = 0;
    }

    public void add(Object data)
    // post: appends the specified element to the end of this list.
    {
        Node temp = new Node(data);
        Node current = head;
        // starting at the head node, crawl to the end of the list
        while(current.getNext() != null)
        {
            current = current.getNext();
        }
        // the last node's "next" reference set to our new node
        current.setNext(temp);
        listCount++;// increment the number of elements variable
    }

    public void add(Object data, int index)
    // post: inserts the specified element at the specified position in this list.
    {
        Node temp = new Node(data);
        Node current = head;
        // crawl to the requested index or the last element in the list,
        // whichever comes first
        for(int i = 1; i < index && current.getNext() != null; i++)
        {
            current = current.getNext();
        }
        // set the new node's next-node reference to this node's next-node reference
        temp.setNext(current.getNext());
        // now set this node's next-node reference to the new node
        current.setNext(temp);
        listCount++;// increment the number of elements variable
    }

    public Object get(int index)
    // post: returns the element at the specified position in this list.
    {
        // index must be 1 or higher
        if(index <= 0)
            return null;

        Node current = head.getNext();
        for(int i = 1; i < index; i++)
        {
            if(current.getNext() == null)
                return null;

            current = current.getNext();
        }
        return current.getData();
    }

    public boolean remove(int index)
    // post: removes the element at the specified position in this list.
    {
        // if the index is out of range, exit
        if(index < 1 || index > size())
            return false;

        Node current = head;
        for(int i = 1; i < index; i++)
        {
            if(current.getNext() == null)
                return false;

            current = current.getNext();
        }
        current.setNext(current.getNext().getNext());
        listCount--; // decrement the number of elements variable
        return true;
    }

    public int size()
    // post: returns the number of elements in this list.
    {
        return listCount;
    }

    public String toString()
    {
        Node current = head.getNext();
        String output = "";
        while(current != null)
        {
            output += "[" + current.getData().toString() + "]";
            current = current.getNext();
        }
        return output;
    }

    private class Node
    {
        // reference to the next node in the chain,
        // or null if there isn't one.
        Node next;

        Object data;


        // Node constructor
        public Node(Object _data)
        {
            next = null;
            data = _data;
        }

        // another Node constructor if we want to
        // specify the node to point to.
        public Node(Object _data, Node _next)
        {
            next = _next;
            data = _data;
        }

        // these methods should be self-explanatory
        public Object getData()
        {
            return data;
        }

        public void setData(Object _data)
        {
            data = _data;
        }

        public Node getNext()
        {
            return next;
        }

        public void setNext(Node _next)
        {
            next = _next;
        }
    }
}

Thanks for taking a look!

That's a lot of code to examine for problems that you have not specified properly - "got messy" doesn't help much, ditto "throws exceptions".
If you post an exact description of the problem(s), with complete copies of all error messages then that will help people know what to look for

Yeah, sorry about all the extra code; I wanted to provide the whole picture all the while rushing to make my check out time for the hotel. Really my focus is with the second chunk of code. I am attempting to create 2 dimensional array from a string array, alphabetically sort the characters of each line using insertion sort. I've tried a few methods and am comfortable in the way I've set up the matrix, but I could use some direction in how I should sort it.

That's a really big post !

anyway , a thing i'd like to ask for clariication :

a) Write code that transforms the string array provided above into a 2 dimensional character matrix, (e.g., char[][] charMatrix;).
b) Once in the two dimensional array form, use insertion sort to sort the characters of each row, from a-z.

isn't this like going round in circles ? a 2-D character matrix is at the end of the day a string array right ?

now then , if i understand your question correctly , here is something you can do :

  1. have a count variable
  2. run a for() loop , taking in each string , and adding the size to count , at the end , count should refer to total number of characters in the string array.
  3. create a character array of size count , populate it with 'count'-many characters , sort it.
  4. take 4 entries at a time from the sorted char array , and knock yourself out with whatever you want to do with them !

ps : personally , i feel silly homeworks like these do more harm than good when it comes to developing a sound programming logic. sadly , most students have to deal with them. ( i know i have , and still do )

Edited 3 Years Ago by somjit{}

a 2-D character matrix is at the end of the day a string array right ?

Wrong! A String is not a char[], and a String[] is not a char[][]. That's a mistake that people quite often make if they come to Java from a C-based language.

Comments
"Wrong!" just woke me up ;D thanks

I mean ofcourse its not ! a string is a class , char is a primitive type... what i meant was , in terms of number of characters for this particular problem , a char[][] equates to a string array ?

Edited 3 Years Ago by somjit{}

... unless the String includes any supplementary characters (which are represented by surrogate pairs of chars). The characters in a String do not necessarily correspond one-to-one with chars. There's more to text on Earth than just ASCII you know.

(OK, maybe I'm just being pedantic, but as a French speaker I get over-sensitive about people who think there are only 26 characters in the alphabet, all represented by char values < 127)

Edited 3 Years Ago by JamesCherrill

... and this link for those who are wondering what surrogate pairs are. The accepted answer is short and sweet :)

OK, maybe I'm just being pedantic

An eye to detail when explaining stuff to young people, imo only helps in helping them learn more. :) i didn't know about surrogate pairs before your post. thank you .

Edited 3 Years Ago by somjit{}

This article has been dead for over six months. Start a new discussion instead.