有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何对每次执行可运行任务时出现的相关值求和?

我有来自here的可运行任务的以下代码,我为自己的目的定制了这些代码,这些代码每秒运行十次。有3个数组,每个数组有10个元素数组只是复制实际代码值的一种人工方法,因此解决方案不需要执行任何数组操作,因为假设我们不知道每次调用task1时每个数组的下一个值是什么

当前代码显示每次调用task1时每个数组的第n个值

如您所见,数组arr_fruits包含重复的结果,因此我想在一行中打印重复结果的每个数组的元素之和

电流输出如下(包含10行):

# : arr_x : arr_y  : fruit
0 : 7     : 2      : Apple
1 : 14    : 4      : Apple
2 : 24    : 9      : Apple
3 : 50    : 22     : Orange
4 : 97    : 45     : Banana
5 : 199   : 91     : Banana
6 : 400   : 179    : Grapes
7 : 792   : 353    : Grapes
8 : 1590  : 713    : Apple
9 : 3176  : 1421   : Orange

Count is 10, cancel the scheduledFuture!

我希望输出是这样的:

# : arr_x : arr_y  : fruit
1 : 45    : 15     : Apple
2 : 50    : 22     : Orange
3 : 296   : 136    : Banana
4 : 1192  : 532    : Grapes
5 : 1590  : 713    : Apple
6 : 3176  : 1421   : Orange

这是单行中显示的每个水果的值之和。 例如:

对于Apple and arr_x:7+14+24=45

对于Grapes and arr_y:179+353=532

在下面的代码中,我放置了一个if-else注释代码,这是我需要帮助的部分。我不知道如何对同一个水果的值求和/累加并打印 和一行,然后在水果变化时打印下一个值

我希望有意义

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorRepeat {
    private static int count = 0;
    private static String fruit = "";
    private static String line = "";
    public static void main(String[] args) throws InterruptedException {

       ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);

        Runnable task1 = () -> {
            int[] arr_x = new int[] {7,14,24,50,97,199,400,792,1590,3176};
            int[] arr_y = new int[] {2,4,9,22,45,91,179,353,713,1421};
            String[] arr_fruits = {"Apple","Apple","Apple","Orange","Banana","Banana","Grapes","Grapes","Apple","Orange"};             

            //if ( fruit == arr_fruits[count] ) {
            //    ///Some code
            //} else {
            //  ///Some other code
            //}

            line = count +  " : " + arr_x[count] + " : " + arr_y[count] + " : " + arr_fruits[count];
            System.out.println( line );
            count++;
        };

        // init Delay = 2, repeat the task every 1 second
        ScheduledFuture<?> scheduledFuture = ses.scheduleAtFixedRate(task1, 2, 1, TimeUnit.SECONDS);

        while (true) {
            Thread.sleep(1000);
            if (count == 10) {
                System.out.println("Count is 10, cancel the scheduledFuture!");
                scheduledFuture.cancel(true);
                ses.shutdown();
                break;
            }
        }

    }
}

共 (0) 个答案