Java 菜鸟,codewars 类(class) #1 - 数组的最小值

标签 java arrays

我正处于 Java 学习阶段,我已经完成了基本教程等,但我需要提高编码的复杂性。虽然 Codewars 第一课似乎超出了我的范围:(

我并不是特别寻找答案(作弊),但也许有人可以批评我所做的(很少),并为我指明正确的方向。问题如下:

Write a function that can return the smallest value of an array or the index of that value. The function's 2nd parameter will tell whether it should return the value or the index.

Assume the first parameter will always be an array filled with at least 1 number and no duplicates. Assume the second parameter will be a string holding one of two values: 'value' and 'index'.

这是我的初始代码...

public class Arrays {

  public static int findSmallest( final int[] numbers, final String toReturn ) {
    //TODO: Add solution here
    int smallest = numbers[0];
    for (int i = 0; i < numbers.length; i++)
    {             
        if (numbers[i] <= smallest)
        {
            smallest = numbers[i];
        }
    }
    return smallest;
    System.out.println(smallest);

    }
}

错误:

/Arrays.java:14: error: unreachable statement System.out.println(smallest); ^ /Arrays.java:16: error: missing return statement } ^ 2 errors

我一直在苦思冥想我在应对这一挑战时所使用的整体逻辑。谁能指出我的方法的错误?感谢您阅读冗长的描述,我确信这是一个简单的问题......

*编辑 - 请注意,我什至还没有开始处理挑战的第一部分,即区分返回值或数组中的位置。

最佳答案

您应该删除 return 语句之后的 System.out.println(smallest);,因为它永远无法到达(或将其放在 return 语句之前)。

public static int findSmallest( final int[] numbers, final String toReturn ) 
{
    int smallest = numbers[0];
    for (int i = 0; i < numbers.length; i++) {             
        if (numbers[i] <= smallest) {
            smallest = numbers[i];
        }
    }
    System.out.println(smallest); 
    return smallest;
}

关于Java 菜鸟,codewars 类(class) #1 - 数组的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30963084/

相关文章:

Java 客户端服务器菜单

javascript - 按字典值排序后如何返回字典数组的新数组

arrays - Swift 解码数组自定义类内存泄漏

arrays - Swift4 initWithArray 等价物

c++ - 减去数组中的每个元素并找到其中最大的

java - 当第二阶段对第一阶段结果值不感兴趣时​​的 CompletionStage 链接

java - Spring MVC : What is an HttpEntity?

java - 方法 "contains"的 Kotlin 逻辑转换为 Java 问题

java - 如何检测 Netbeans 中的 Java 应用程序锁定?

ruby-on-rails - Rails 4 字符串复选框从不返回空数组