0

我有一个数组:

class Words
{
   public static string[] wordsArray = { "one", "two", "three", "four" };
}

显示值数组的 TextBlock 和显示数组下一个值的按钮:

private int counter = 0;

    private void goButton_Click(object sender, RoutedEventArgs e)
    {

        if (counter < Words.wordsArray.Length)
        {
            enWordTextBlock.Text = Words.wordsArray[counter++];
        }
    }

当方框出现在数组的最后一个值上时,程序会继续不工作,如何让它在一个“圆圈”内工作?

谢谢大家!

4

2 回答 2

6

这应该有效:


private void goButton_Click(object sender, RoutedEventArgs e)
{
    counter++; //increase the counter
    int i = counter % Words.wordsArray.Length; //modulo operation
    enWordTextBlock.Text = Words.wordsArray[i]; //set text
}

于 2012-07-08T11:30:59.730 回答
3
private int counter = 0;

private void goButton_Click(object sender, RoutedEventArgs e)
{
    enWordTextBlock.Text = Words.wordsArray[counter++ % Words.wordsArray.Length];
}



[编辑]
好的,这是与 user1397396 评论相关的编辑。我不确定我是否正确理解您,但您可能对负值模数有疑问。例如:

int counter = 0;
int mod = 4;
counter--; // counter is -1 after this line is executed
int result = counter % mod; // result is -1
result = (counter + mod) % mod; // result is now 3 as desired



以下是我将如何实现这些 Next 和 Previous 按钮。

private int counter = 0;

private void NextButton_Click(object sender, RoutedEventArgs e)
{
    enWordTextBlock.Text = Words.wordsArray[counter % Words.wordsArray.Length];
    counter++; // put ++ operator in new line to avoid confusion
}

private void PreviousButton_Click(object sender, RoutedEventArgs e)
{
    int wordCount = Words.wordsArray.Length;
    // add wordCount before applying modulus (%) to avoid negative results
    // -1 % 5 = -1; -2 % 5 = -2; -6 % 5 = -1 etc
    // negative values would cause exception when accessing array
    counter = ((counter - 1) + wordCount) % wordCount; 
    enWordTextBlock.Text = Words.wordsArray[counter];
}

例如,此代码将导致按 Next、Previous、Next 为您提供:“one”、“four”、“one”。


更好的解决方案是使用如下方法(或内联代码):

private static int GetPositiveIntModulus(int value, int mod)
{
    return ((value % mod) + mod) % mod;
}

对于任何值,它都会给你一个积极的结果,即使是value < -mod. 所以你可以这样写上面的代码:

private int counter = 0;

private void NextButton_Click(object sender, RoutedEventArgs e)
{
    // uncomment this to ensure valid counter
    // if it is changed somewhere else in the program
    //counter = GetPositiveIntModulus(counter, Words.wordsArray.Length);
    enWordTextBlock.Text = Words.wordsArray[counter];
    counter = GetPositiveIntModulus(counter + 1, Words.wordsArray.Length);
}

private void PreviousButton_Click(object sender, RoutedEventArgs e)
{
    counter = GetPositiveIntModulus(counter - 1, Words.wordsArray.Length);
    enWordTextBlock.Text = Words.wordsArray[counter];
}
于 2012-07-08T11:34:06.997 回答