麻烦的递归方法

时间:2017-12-24 22:29:40

标签: java arrays recursion

public static boolean array6(int[] nums, int index) {
    if(nums.length > index+1) 
    {
        if(nums[index] == 6)
            return true;
        else
            array6(nums,index+1);
    }
    else if(nums.length==index+1)
    {
        if(nums[index] == 6)
            return true;
        else
            return false;
    }
    return false;
}

作为我的CSA类的练习的一部分,我们必须编写一个方法来查找int数组中是否存在6并返回相应的布尔值。如果数组中的第一个数字是6,那么我写的方法是有效的,但是否则它没有。为什么呢?

注意:必须以递归方式完成

2 个答案:

答案 0 :(得分:1)

问题是你没有触发递归,因为你在代码中没有返回方法本身的结果。如果条件为if statement,则重写true的内容,如下所示将使其按预期工作:

if (nums.length > index_next) 
{
    if (nums[index] == 6)
        return true;

    // you have to return the result of the function here
    // in order to obtain an effective recursion, otherwise the
    // method is called but it's output value is ignored and the
    // functions goes outside the scope of the if statement
    // reaching the "return false" located at the bottom
    return array6(nums, index_next);
}

但总的来说,你的功能包含很多问题。您的任务非常简单,但您以极其复杂的方式编写它。你可以使用很多内置函数来实现相同的结果......即使你不想使用它们,一个简单的for loop也可以完成这项任务:

boolean found = false;

for (int i = 0; i < nums.length; ++i)
{
    if (nums[i] == 6)
    {
        found = true;
        break;
    }
}

编辑:重复实施

public static boolean array6(int[] nums, int index)
{
    if (index == nums.length)
        return false;

    if (nums[index] == 6)
        return true;

    return array6(nums, index + 1);
}

答案 1 :(得分:0)

紧凑型解决方案

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;

namespace MvcMovie.Models
{
public static class SeedData
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (var context = new MvcMovieContext(

           serviceProvider.GetRequiredService<DbContextOptions<MvcMovieContext>>()))
        {
            // Look for any movies.
            if (context.Movie.Any())
            {
                return;   // DB has been seeded
            }
  ...
相关问题