从数组中提取序列

时间:2015-03-28 05:52:38

标签: java arrays sequence extraction

我正在编写从文件读取整数数组的代码,检查数字序列的增加,并打印数组的长度以及数字本身的序列。我写的代码似乎正确地打印了数组,显示已经找到了文件中的数组,并计算了最长的数字序列,但它并没有完全正确的序列。下面是完整的代码和输出。

public static void main(String[] args) throws IOException {
    File file = new File("input.txt");
    Scanner s = null;
    final int MAX_SIZE = 100;
    int count = 0;
    int[] tempArray = new int[MAX_SIZE];
    try {
        s = new Scanner(file);
        int arrayAddress = 0;
        System.out.println("File found!");
        while (s.hasNextInt()) {
            count++;
            tempArray[arrayAddress] = s.nextInt();
            arrayAddress++;
        }
        s.close();
    }
    catch (FileNotFoundException noFile) {
        System.out.println("File not found.");
    }

    int[] inputArray = new int[count];
    for (int i = 0; i < count; i++)
    {
        inputArray[i] = tempArray[i];
    }

    int sequence = 0;
    int maxSequence = 0;
    int sequenceEnd = 0;

    for (int j = 0; j < count; j++) {
        for (int k = j; k < count - 1; k++) {
            if (inputArray[k + 1] == inputArray[k] + 1 ) {
                sequence++;
                sequenceEnd = k;
            }
            if (sequence > maxSequence) {
                maxSequence = sequence;
                sequence = 0;
            }
        }
    }

    int temp = 0;
    System.out.println("The array is: " + Arrays.toString(inputArray));
    System.out.println("The longest sequence of increasing numbers is " + maxSequence);
    System.out.println("The sequence is as follows: ");
    for (int i = sequenceEnd - maxSequence; i < sequenceEnd; i++) {
        temp = inputArray[i];
        System.out.println(temp);
    }
}

我的序列上面代码的输出如下:

File found!
The array is: [7, 2, 13, 4, 5, 18, 11, 1, 20, 17, 15, 10, 19, 8, 16, 12, 6, 14, 9, 3]
The longest sequence of increasing numbers is 2
The sequence is as follows: 
2
13

我真的希望这不是一个小小的疏忽,但我似乎无法弄清楚我在哪里犯了错误。如果您有时间查看并帮助我,请提前致谢。

1 个答案:

答案 0 :(得分:0)

您的代码中存在两个问题:

(1)查找序列的最大长度

重置序列长度

if(sequence&gt; maxSequence){        maxSequence = sequence;        sequence = 0;    }

不应位于内循环内。那是你还在计算元素的那个。您想将其移动到外部循环,即从

for (int j = 0; j < count; j++) {
    for (int k = j; k < count - 1; k++) {
    //current location
    }
}

for (int j = 0; j < count; j++) {
    for (int k = j; k < count - 1; k++) {
    }
    //assumingly desired location
}

(2)打印序列

打印循环的偏移量偏离一个元素,应为

for (int i = sequenceEnd - maxSequence1; i < sequenceEnd; i++) {
    temp = inputArray[i-1];
    System.out.println(temp);
}

一旦maxSequence包含正确数量的元素(即当前不是2),它将打印整个序列。