从txt文件中读取数字并进行比较

时间:2016-01-04 13:37:07

标签: java

通过这个程序,我想阅读并比较我在文本文件中给出的数字并打印出来 只要数字连续三次上升,&#34;立即购买&#34; &#34;只要数量连续三次下降,&#34; <#em>

我的程序的问题是它只读取&#34; numbers.txt&#34;的15行中的13行。买卖是在错误的地方。

CONFIG.value = 1

文件numbers.txt:

  

26.375
  25.500
  25.125
  25.000
  25.250
  27.125
  28.250
  26.000
  25.500
  25.000
  25.125
  25.250
  26.375
  25.500
  25.500

预期产出:

  

1 26.375
  2 25.500
  3 25.125
  4 25.000
  5 25.250买
  6 27.125
  7 28.250
  8 26.000出售
  9 25.500
  10 25.000
  11 25.125买
  12 25.250
  13 26.375
  14 25.500出售
  15 25.500

2 个答案:

答案 0 :(得分:0)

您使用的a + 1 < array.length - 1可以转换为a < array.length - 2。我想你明白了&amp;&amp ;;中的第二个操作数。将迭代限制为13。

a < array.length && a < array.length - 2 = a < 15 && a < 13 = a < 13

我对您的代码进行了一些小的更改以使其正常工作;你可以重构它很多,但我坚持你的风格,所以你可以更好地理解逻辑。

    int num = 1;
    //print the 1st element
    System.out.println(num + "  " + array[0]);
    for (int a = 1; a < array.length; a++) {
        num++;
        System.out.print(num + "  " + (array[a]));
        //plz note that we check with the before, not after
        if (array[a] < array[a - 1]) {
            down++;
        } else if (array[a] > array[a - 1]) {
            up++;
        } else {
            same++;
        }
        //changed down > to down ==
        if ((up >= 3 && (down == 1 || same >= 1))) {
            System.out.print("  " + "sell");
            up = 0;
            same = 0;
        } 
        //changed up > to up ==
        else if ((down >= 3 && (up == 1 || same >= 1))) {
            System.out.print("  " + "buy");
            down = 0;
            same = 0;
        }
        System.out.println();
    }

回答OP评论:如果你想支持超过15条记录,你可以继续添加到列表中:

List<Double> list = new ArrayList<>();
while (scanner.hasNextDouble()) {
    list.add(scanner.nextDouble());
}
//if you want to work with array
Double[] array = new Double[list.size()];
array = list.toArray(array);

答案 1 :(得分:0)

这是一个工作示例(必须将数组更改为列表)

int num = 0, up = 0, down = 0, same = 0;

FileInputStream file = new FileInputStream("numbers.txt");
Scanner scanner = new Scanner(file);
List<Double> list = new ArrayList<>();

while (scanner.hasNextDouble()) {
    list.add(scanner.nextDouble());
}

int position = 0;

while (position + 2 < list.size()) {
    Double[] nums = new Double[3];

    System.out.println(nums[0] = list.get(position));
    System.out.println(nums[1] = list.get(position + 1));
    System.out.println(nums[2] = list.get(position + 2));

    if (nums[1] > nums[0] && nums[2] > nums[1]) {
        System.out.println("buy");
        up++;
    } else if (nums[1] < nums[0] && nums[2] < nums[1]) {
        System.out.println("sell");
        down++;
    } else {
        same++;
    }
    position += 2;
}
System.out.println("Ups total: " + up);
System.out.println("Downs total: " + down);
System.out.println("Same total: " + same);