When I try to run my WordSort class with another class using the code:

WordSort ws = new WordSort(sentence);
ws.sort();

The program prints out what I want it to in the first method but for the ws.sort() method, the program prints out null. I would like it to print out what wordArray[0] would be in the first method.

Here's the code

public class WordSort
{
    public String[] wordArray;
    public WordSort(String sentence)
    {
        wordArray = new String[sentence.length()];
        String[] wordArray = sentence.split(" ");
        for (int i=0; i<wordArray.length; i++)
        {
            System.out.println(wordArray[i]);
        }
        System.out.println(wordArray.length);
        return;
    }

    void sort()
    {
        System.out.println(wordArray.length);
        /*for (int i=0; i<wordArray.length; i++)
        {
            System.out.println(wordArray[i]);
        }*/
        System.out.println(wordArray[0]);
        /*for (int k = 0; k<wordArray.length-1; k++)
        {
            int min = k;
            for (int j = k+1; j<wordArray.length; j++)
            {
    }

    public String toString()
    {
        String output="";
        for(String s : wordArray )
        {
            output+=s+"n";
        }
        System.out.print(output);
        return output+"nn";
    }
}

Here's the class I'm using to run the first class:

public class WordSortDriver
{
    public static void main( String args[] ) throws IOException
    {
        Scanner file = new Scanner(new File("Data.txt"));
        int size = file.nextInt();
        file.nextLine();
        for(int i = 0; i<size; i++)
        {
            String sentence = file.nextLine();
            WordSort ws = new WordSort(sentence);
            ws.sort();
        }
    }
}

Thanks for answering!

Edited 3 Years Ago by Reverend Jim: Fixed formatting

The correct way to do it is:

public WordSort(String sentence)
{
	wordArray = sentence.split(" ");
	
}

Your code was the following, which creates a completely different variable called wordArray than the variable you declared at the top of your class. If you don't get that then go read about variable scope.

public WordSort(String sentence)
{
	String[] wordArray = sentence.split(" ");
	
}

Saying String[] wordArray = new String[sentence.length()]; doesn't make sense because sentence.length() is the number of characters in the String, not the number of words. So potentially the user could enter "ghjskdfghgjfhddhfgjh" and your code would create a String[] with a ton of space that wasn't ever used.

Edited 6 Years Ago by BestJewSinceJC: n/a

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