如何使用OOP打印arrayList中的最低值?

时间:2017-01-31 02:59:36

标签: java loops oop arraylist

我期望得到最低的运行时间,但它会打印出arrayList中的最后一个主菜。我正在尝试为狗打印一个特定的课程,这在我输入课程代码时有效。但是,最低运行时间似乎不起作用。

示例数据

Lazlo 12.2

凛34.2

Yu 23.3 - 当Lazlo成为获胜的狗时,这将被打印为获胜的狗。

获胜的狗应该具有最低的运行时间,但它会取代最后一条读取线并打印出来。

private void winningDog(String dogsCode) 
{
    double runTime = 300;
    String winningDog = "";
    double winningTime = 0;
    for (Dogs dog: dogsList)
    {
        if(runTime > dog.getTotalTime() && (dog.getCourseCode().equalsIgnoreCase(dogsCode)))
        {
            winningTime = dog.getTotalTime();
            winningDog = dog.getName();
        }

    }
    System.out.printf("%n%s%17s%20s%1.2f%n", 
          "Winning dog", winningDog,"Time " , winningTime);

}

3 个答案:

答案 0 :(得分:0)

你要做的是基本上找到某个对象的最小字段。您可以使用新的Java 8 Stream API在一行中完成此操作。

Dogs winningDog = dogsList.stream().min(Comparator.comparingInt(Dogs::getTotalTime)).get();

您的班级Dogs应该是Dog。我只是根据您的增强型for循环开始我的响应,其中显示Dogs dog: dogsList

通过在.filter( CONDITIONS ).stream()之间添加.min(),可以轻松地将for循环中的过滤器链接到呼叫中。

答案 1 :(得分:0)

假设您没有winningTime = Double.MAX_VALUE; //assigning MAX value to ensure the condition is met at least once(unless all your time values are MAX_VALUE) 的负值,则可以更改代码

if(runTime > dog.getTotalTime()..

然后将您的条件更新为

if(winningTime > dog.getTotalTime().. // this would compare winningTime and you're setting the same is the condition matches

h5 = h5py.File('myfile.h5', 'r')
mydata = h5.get('matirx') # are all data loaded into memory by using h5.get?
part_of_mydata= mydata[1000:11000,:]
size_data =  mydata.shape 

答案 2 :(得分:0)

private void winningDog(String dogsCode) {
    String winningDog = "";
    double winningTime = 0;
    if (dogsList != null) {
        winningTime = dogsList.get(0).getTotalTime();
        winningDog = dogsList.get(0).getName();
        if (dogsList.size() > 1) {
            for (int i = 1; i < dogsList.size(); i++) {
                if (dogsList.get(i).getTotalTime()< winningTime
                        &&  (dogsList.get(i).getCourseCode().equalsIgnoreCase(dogsCode))) {
                    winningTime = dogsList.get(i).getTotalTime();
                    winningDog = dogsList.get(i).getName();
                }

            }
        }
    }
    System.out.printf("%n%s%17s%20s%1.2f%n", "Winning dog", winningDog, "Time ", winningTime);
}