Search code examples
javafor-loopprintingcrossword

How to get 2 words to cross at intersecting characters. (One vertically and the other horizontally)


I'm working on a homework assignment for school, the assignment states "get two words as input and prints one vertically and one horizontally so that they intersect".

An Example of this:

vertical: coffee
horizontal: suffering
  c
  o
suffering
  f
  e
  e

When I enter in coffee and suffering I get this as an output:

vertical: coffee
horizontal: suffering
   c
   o
suffering
   f
   f
   e
   e

My code is as follows:

public static void main(String[] args) {

    Scanner kb = new Scanner(System.in);

    System.out.print("vertical: ");
    String vertical = kb.next().toLowerCase();

    System.out.print("horizontal: ");
    String horizontal = kb.next().toLowerCase();

    boolean indexed = true;
    int indexOf = 0;
    StringBuilder spaces = new StringBuilder();

    while (indexed) {
      for (int i = 1; i <= vertical.length()-1; i++) {
        String found = vertical.substring(i - 1, i);
        spaces.append(" ");
        if (horizontal.contains(found)) {
          indexOf = i;
          indexed = false;
          break;
        }
      }
    }

    for (int i = 1; i <= vertical.length(); i++) {
      if (i == indexOf) {
        System.out.println(horizontal);
      }
      System.out.println(spaces + vertical.substring(i - 1, i));
    }
  }

Solution

  • Here are some pointers.

    1. Use indexOf to find the intersection point.

    2. The index of horizontal word is how far to indent the vertical characters. Once the index is found, the spacing is easily obtained by doing something like the following:

         spaces = "                        ".substring(0,indexOf);
    
    1. The index of the vertical word is at what point to print the horizontal word and NOT the vertical character.

    2. Remember to handle the special case when no character is in common.

    3. You don't need a nested while and for loop. One or the other is all that is needed.