用来自用户的数据逐渐填充数组

时间:2010-05-15 00:26:27

标签: java arrays conditional fill java.util.scanner

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

1 个答案:

答案 0 :(得分:1)

  • 您没有从height阅读Scanner(有什么价值?)
  • 您确定不允许使用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);
    }

相关问题