开发者

comparing strings, one from an array other from an entered value

开发者 https://www.devze.com 2023-02-21 21:17 出处:网络
Basically comparing a string that is entered, and trying to get that position from the array. If I initialize position to 0 then it returns the position zero of the array, if I initialize to 1 then i

Basically comparing a string that is entered, and trying to get that position from the array.

If I initialize position to 0 then it returns the position zero of the array, if I initialize to 1 then it gives me the item in slot 1, so it's skipping the compare statement.

I also tried using (custStatus == cardStatus[i])

public static int discount(string 开发者_如何学Go[]cardStatus, int []pDiscount, string custStatus)
{
    int position= 0;
    int discount;
    for(int i = 0; i < 2; i++)
    {
        if (string.Equals(custStatus, cardStatus[i]))
            position = i;
    }
    discount = pDiscount[position];
    return discount;
}


With your code, there's no way to tell if position = 0 means custStatus was found in your cardStatus array or if no match was made at all and the default value is being used. I'd recommend either using a boolean matchFound variable or setting position = -1 and adding an extra if statement at the end either way. Either:

boolean matchFound = false;
...
if(matchFound)
{
    discount = pDiscount[position];
}

or else

int position = -1;
...
if(position >= 0)
{
    discount = pDiscount[position];
}


Give this a try:

public static int discount(string[] cardStatus, int[] pDiscount, string custStatus) {
  var position = Array.IndexOf(cardStatus, custStatus);
  return (position == -1) ? -1 : pDiscount[position];
}


public static int discount(string []cardStatus, int []pDiscount, string custStatus)
{
    for(int i = 0; i < Math.Min(cardStatus.Length, pDiscount.Length); i++)
    {
        if (string.Equals(custStatus, cardStatus[i]))
        {
            return pDiscount[i];
        }
    }

    return -1;
}

Don't be afraid to return directly from FOR-loop, it is old-school that teaches to have only one return point from method. You can have as many returns as it helps you to keep your code clean and easy to read.

And perhaps it would be better to use the following expression in for-loop as it will guard you from possible different lengths of arrays:

for (int i = 0; i < Math.Min(cardStatus.Length, pDiscount.Length; i++)


This looks ok, even though this is somewhat more straightforward:

for(int i = 0; i < cardStatus.Length; i++)
{
    if (custStatus == cardStatus[i])
    {
        position = i;
        break;
    }
}

Given your question it appears to be the case that all cardStatus[i] match custStatus - did you check the input?

Also given your code what happens if there is no match? Currently you would return pDiscount[0] - that doesn't seem to be correct.

0

精彩评论

暂无评论...
验证码 换一张
取 消