Продолжайте получать IndexOutOfBoundsException в APlusCompSci Проблема нечетного до четного массива [дубликат]

Прочитав каждый ответ и попробовав их, никто из них не помог мне. То, что я нашел во время поиска в другом месте, заключается в том, что вы можете создать настраиваемый атрибут, который затем добавить в свой контроллер. Он перезаписывает EnableCors и добавляет в него белые списки.

Это решение работает хорошо, потому что оно позволяет вам иметь белые списки в webconfig (appsettings) вместо того, чтобы их кодировать в атрибуте EnableCors на вашем контроллере .

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class EnableCorsByAppSettingAttribute : Attribute, ICorsPolicyProvider
{
    const string defaultKey = "whiteListDomainCors";
    private readonly string rawOrigins;
    private CorsPolicy corsPolicy;

    /// 
    /// By default uses "cors:AllowedOrigins" AppSetting key
    /// 
    public EnableCorsByAppSettingAttribute()
        : this(defaultKey) // Use default AppSetting key
    {
    }

    /// 
    /// Enables Cross Origin
    /// 
    /// AppSetting key that defines valid origins
    public EnableCorsByAppSettingAttribute(string appSettingKey)
    {
        // Collect comma separated origins
        this.rawOrigins = AppSettings.whiteListDomainCors;
        this.BuildCorsPolicy();
    }

    /// 
    /// Build Cors policy
    /// 
    private void BuildCorsPolicy()
    {
        bool allowAnyHeader = String.IsNullOrEmpty(this.Headers) || this.Headers == "*";
        bool allowAnyMethod = String.IsNullOrEmpty(this.Methods) || this.Methods == "*";

        this.corsPolicy = new CorsPolicy
        {
            AllowAnyHeader = allowAnyHeader,
            AllowAnyMethod = allowAnyMethod,
        };

        // Add origins from app setting value
        this.corsPolicy.Origins.AddCommaSeperatedValues(this.rawOrigins);
        this.corsPolicy.Headers.AddCommaSeperatedValues(this.Headers);
        this.corsPolicy.Methods.AddCommaSeperatedValues(this.Methods);
    }

    public string Headers { get; set; }
    public string Methods { get; set; }

    public Task GetCorsPolicyAsync(HttpRequestMessage request,
                                               CancellationToken cancellationToken)
    {
        return Task.FromResult(this.corsPolicy);
    }
}

    internal static class CollectionExtensions
{
    public static void AddCommaSeperatedValues(this ICollection current, string raw)
    {
        if (current == null)
        {
            return;
        }

        var paths = new List(AppSettings.whiteListDomainCors.Split(new char[] { ',' }));
        foreach (var value in paths)
        {
            current.Add(value);
        }
    }
}

Я нашел это руководство онлайн и работал как шарм:

http://jnye.co/Posts/2032/dynamic-cors-origins -from-appsettings-using-web-api-2-2-cross-origin-support

Я думал, что убью это для всех, кто в этом нуждается.

1
задан Tradell 2 March 2019 в 07:48
поделиться

4 ответа

Вот решение. Вам не нужно 2 петли

public class App 
{
    public static void main( String[] args )
    {
        int arr[] = {3, 5, 7, 1};
        System.out.println( go(arr) );
    }

    static int go(int[] array) {
        int oddPos = -1;
        for (int i = 0; i < array.length; i++) {
            //check if already din't find an odd number and if current number is odd
            if (oddPos == -1 && array[i] % 2 == 1) {
                oddPos = i;
            }
            // check if already found an odd number and current number is even
            if (oddPos != -1 && array[i] % 2 == 0) {
                return i - oddPos;
            }
        }
        return -1;
    }
}
0
ответ дан Thanthu 2 March 2019 в 07:48
поделиться

Посмотрите на три (упрощенные) строки вашего кода:

for (int a = 0; a < arrays.length; a++) {

    for (int b = a+1; ...) {

        array[b]

Теперь, когда a находится в конце массива, и вы делаете b = a+1, b - после конца массив, и выполнение array[b] вызовет исключение.

Пример:

  • array = [1]
  • a = 0
  • b = 1
  • array [1] ??? вне границ
0
ответ дан Ridcully 2 March 2019 в 07:48
поделиться

Вы, кажется, неправильно поняли, что означает distance = e - o. Это не значит, что distance будет меняться в зависимости от e и o. Это просто означает, что все значения e и o, которые хранятся в данный момент, используются для вычисления значения distance, и distance будет иметь то же значение, пока вы его не измените. Изменение e или o после этой строки не влияет на distance. Следовательно, distance всегда будет -1.

Вы также, кажется, используете вложенные циклы. Это не нужно здесь. Вот общий алгоритм:

for each element x in the array
    if x is odd then
        record x's position in y
    if an odd number has been found and x is even then
        return x's position minus y

А вот код:

public static int oddEven(int[] numbers) {
    int oddPosition = -1;
    for (int i = 0 ; i < numbers.length ; i++) {
        if (numbers[i] % 2 == 1) {
            oddPosition = i;
        }
        if (oddPosition != -1 && numbers[i] % 2 == 0) {
            return i - oddPosition;
        }
    }
    return -1;
}
0
ответ дан Sweeper 2 March 2019 в 07:48
поделиться

Вот решение псевдокода

for each number in array
     if is looking for odd and number is odd
         remember position
         set is looking for odd to false

     if is looking for even and number is even
        distance = remembered position - current position
        quit loop
0
ответ дан Joakim Danielson 2 March 2019 в 07:48
поделиться
Другие вопросы по тегам:

Похожие вопросы: