Search code examples
javaarraysconditional-statementsfilljava.util.scanner

filling array gradually with data from user


I'm trying to fill an array with words inputted by user. Each word must be one letter longer than previous and one letter shorter than next one. Their length is equal to table row index, counting from 2. Words will finally create a one sided pyramid, like :
A
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 limit words read from scanner to fill the requirements?Currently the while loop doesn't influence scanner at all :/

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


Solution

    • You didn't read height from Scanner (what's the value?)
    • Are you sure you're not allowed to use List<String> and other dynamically growable data structures?
    • What's supposed to happen if the length requirement isn't met?
    • Why the 2 and -2 offset?
      • When i = 2, you also access words[i-3]. which will throw ArrayIndexOutOfBoundsException

    Here's a rewriting 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