Gradually filling arrays with data from the user

I am trying to fill an array with user input words. Each word must be one letter longer than the previous one and one letter shorter than the next. Their length is equal to the index of the table row, counting from 2. Words will finally create a one-sided pyramid, for example:

AB
ABC
ABCD

Scanner sc = new Scanner(System.in);
System.out.println("Give the height of array: ");
height = sc.nextInt();
String[] words = new String[height];
for(int i=2; i<height+2; i++){
    System.out.println("Give word with "+i+" letters.");
    words[i-2] = sc.next();
    while( words[i-2].length()>i-2 || words[i-2].length()<words[i-3].length() ){
        words[i-2] = sc.next();
    }
}

      

How can I restrict the reading of words from the scanner in order to complete the requirements? Currently the while loop does not affect the scanner at all: /

This is not homework. I am trying to create a simple application and then a gui for it.

+2


a source to share


1 answer


  • You haven't read height

    from Scanner

    (what's the meaning?)
  • Are you sure you are not allowed to use List<String>

    other dynamically growing data structures as well?
  • What should happen if the length requirement is not met?
  • Why offset 2

    and -2

    ?
    • When i = 2

      , you also get access to words[i-3]

      . who will throwArrayIndexOutOfBoundsException


Here's a rewrite that makes the logic clearer:



    Scanner sc = new Scanner(System.in);

    System.out.println("Height?");
    while (!sc.hasNextInt()) {
        System.out.println("int, please!");
        sc.next();
    }
    final int N = sc.nextInt();

    String[] arr = new String[N];
    for (int L = 1; L <= N; L++) {
        String s;
        do {
            System.out.println("Length " + L + ", please!");
            s = sc.next();
        } while (s.length() != L);
        arr[L - 1] = s;
    }

    for (String s : arr) {
        System.out.println(s);
    }

      

Related questions

+1


a source







All Articles