clopez
clopez

Reputation: 25

Where's the error in this program that prints a matrix?

I created a matrix program that takes in the words from a file and prints them out either horizontally or vertically. The program checks if the character of a word is already in a spot or if the spot is blank in order to make sure it prints out properly. If a word or character is printed on top of another word or character then a new spot is generated to put the word in. This is done until the word can be printed without error. The blank spaces are filled with the letter 'A'.

import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class WordSearch {

public WordSearch() {

}

public void getMatrix() throws FileNotFoundException {



    File file = new File("/home/cameron/Desktop/words");

    ArrayList<String> words = new ArrayList<String>();

    String largest = "";

    char[][] data;

    int col = 0;




    Scanner sc = new Scanner(file);


    while (sc.hasNextLine()) {


        String first = sc.nextLine();

        words.add(first);


        if(first.length()>largest.length()){



         largest=first;

         col=largest.length();

        }
    }



        data = new char[col][col];

        int curWord=0;


        for(int i=0; i<words.size(); i++){
            String word=words.get(curWord);  
            int start=0;
            int row=0;
            int choice=0;
            int index=0;


         do
         {

           start = (int)(Math.random()*data.length);
           row =  (int)(Math.random()*data.length);
           choice = (int)(Math.random()*2);

         }
         while(start+word.length()>data.length);



         index=0;

         if(choice==0){
             for(int j=start; j<start+word.length(); j++){              
                 if(data[row][j]==0 || data[row][j]==word.charAt(index)){
                     data[row][j] = word.charAt(index);

                     index++;
                 }

                 else{ i=0; continue;}


             }
         }

         if(choice==1){
             for(int j=start; j<start+word.length(); j++){
                 if(data[j][row]==0 || data[j][row]==word.charAt(index)){
                    data[j][row] = word.charAt(index);

                    index++;
                 }

                 else{ i=0; continue;}
             }
         }

           curWord++;
          }



       for(int i=0; i<data.length; i++){
         for(int j=0; j<data[i].length; j++){
            if(data[i][j]==0)
             System.out.print("A ");
            else    
             System.out.print(data[i][j]+" ");
         }

         System.out.println();
        }


    }


 public static void main(String[] args) throws FileNotFoundException {



    WordSearch check = new WordSearch();

    check.getMatrix();

 }
}  

I set up an if else statement for if the character of the word were to printed on top of a different character or word then the for loop (the one above the do while) would be restarted in order to make sure that the word is printed out correctly.

I am having one problem, though. The program seems to work about 50% and prints out something like this:

A A h A A A A f A 
A A a A A l A e A 
A A m A A a A n A 
A A b A A d A c A 
A A u A A y A e A 
A A r A A b A A A 
A A g A A u A A A 
A A e A A g A A A 
A A r A A A A A A 

Occasionally I get this error and this error only (at this specific index):

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at WordSearch.getMatrix(WordSearch.java:59)
at WordSearch.main(WordSearch.java:132)

What could be the problem?

Edit: Here is what is being read into the program from the file:

ladybug
hamburger
fence

Upvotes: 1

Views: 64

Answers (1)

pczeus
pczeus

Reputation: 7868

OK, I cleaned up your code a little bit by extracting the common logic in your for loops into a method for readability and reuse. Also, the else condition was causing you an issue and was unnecessary by resetting the 'i' back to 0 and causing an occasional error.

Please try this modified code and let me know if you continue to get an error. After running it about 20 times consecutively, I no longer see an issue:

    import java.util.*;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;

    public class WordSearch {
        ArrayList<String> words = new ArrayList<>();

        private void getMatrix(String filePath) throws FileNotFoundException {
            File file = new File(filePath);
            String largest = "";
            char[][] data;
            int col = 0;
            Scanner sc = new Scanner(file);

            while (sc.hasNextLine()) {
                String first = sc.nextLine();
                words.add(first);

                if(first.length() > largest.length()){
                    largest = first;
                    col = largest.length();
                }
            }

            data = new char[col][col];
            int curWord = 0;

            for(int i = 0; i < words.size(); i++){
                String word = words.get(curWord);
                int start = 0;
                int row = 0;
                int choice = 0;

                do{
                    start = (int)(Math.random()*data.length);
                    row =  (int)(Math.random()*data.length);
                    choice = (int)(Math.random()*2);
                }
                while(start + word.length() > data.length);

                updateData(choice, start, row, word, data);
                curWord++;
            }

            for (char[] aData : data) {
                for (char anAData : aData)
                    if (anAData == 0)
                        System.out.print("A ");
                    else
                        System.out.print(anAData + " ");
                System.out.println();
            }
        }

        private void updateData(int choice, int start, int row, String word, char[][] data){

            for(int index = 0, j = start; j < start + word.length(); j++){
                switch(choice){
                    case 0:
                        if(data[row][j] == 0 || data[row][j] == word.charAt(index)){
                            data[row][j] = word.charAt(index);
                            index++;
                        }
                        break;
                    case 1:
                        if(data[j][row] == 0 || data[j][row] == word.charAt(index)){
                            data[j][row] = word.charAt(index);
                            index++;
                        }
                        break;
                }
            }
        }

        private String getRandomLetter(){
            Random r = new Random();
            char c = (char) (r.nextInt(26) + 'a');
            return ("" + c).toUpperCase();
        }

        public static void main(String[] args) throws FileNotFoundException {
            WordSearch check = new WordSearch();
            check.getMatrix("/home/cameron/Desktop/words");
        }
    }  

The program is pretty neat, good job. To make it a little more interesting, I added/changed a couple of things, which you can use or not use to your liking.

Notice I added the getRandomLetter() method. That way you can use random letters instead of just 'A' every time to fill in the matrix and looks more like true word-search. I also upper-cased the original words and each random letter, by changing the line where you add the word from the file to the words list:

words.add(first.toUpperCase());

Now the output looks like:

K M D X H A L B H 
C M L G A W N F F 
M V W Z M D T O T 
L A D Y B U G T Y 
Y J U J U R D V C 
C I C O R P P I L 
B B P R G R Q L X 
D B D V E X R V K 
E I J H R G L D B 

Upvotes: 2

Related Questions