2

我正在尝试用用户输入的单词填充数组。每个单词必须比前一个长一个字母,比下一个短一个字母。它们的长度等于表行索引,从 2 开始计数。单词最终会创建一个单面金字塔,例如:
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();
    }
}

如何限制从扫描仪读取的单词以满足要求?目前 while 循环根本不影响扫描仪:/

这不是家庭作业。我正在尝试创建一个简单的应用程序,然后为它创建 gui。

4

1 回答 1

1
  • 您没有阅读heightScanner价值是什么?)
  • 您确定不允许使用List<String>其他可动态增长的数据结构吗?
  • 如果不满足长度要求会发生什么?
  • 为什么2-2偏移?
    • 什么时候i = 2,你也访问words[i-3]。这会抛出ArrayIndexOutOfBoundsException

这是一个使逻辑更清晰的重写:

    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);
    }

相关问题

于 2010-05-15T00:34:04.667 回答