c# - pig 拉丁语翻译。 C#作业

标签 c# visual-studio

Create a GUI application called IGPAY that lets a user enter a word. Then, when the user clicks a button, your program will generate and display the Pig Latin equivalent of that word. (To do this you remove the first letter of the word, then add that letter to the end of the word plus the letters "ay." For example, fish would become ishfay and ball would become allbay.) Make sure the GUI is attractive in appearance and that all labels, textboxes, buttons, and similar are clearly labeled. Hint: store the word in a string and consider using the Substring method. Also remember that the Length property of a string will tell you its length. See pages 79-80 of the text for examples.

这是我想出的代码。我是这种语言的新手并且对 Python 有一点了解,但我只是不明白为什么它会抛出“超出范围异常”错误。我正在努力做到这一点,以便代码接受任何单词并以 pig Latin 显示它。

private void button1_Click(object sender, EventArgs e)
{
       string word; 
       string first;
       string rest;
       string full;
       word = textBox1.Text;
       first = word.Substring(0);
       rest = word.Substring(1, word.Length);
       full =  rest + first + "ay";
       label2.Text = full;
}

最佳答案

不确定为什么你会被否决,干得好,声明这是家庭作业,至少提供一些你已经完成的工作。除此之外,这里的每个人都应该感谢您想要学习。

如果我是你,我会考虑一些事情。除了应该修复您的异常的 Phylyp 的答案之外,如果用户输入的字符少于两个,您还应该处理,这也可能导致异常。

下面我展示了您可以做的三件事的示例。不是说这是最好的方式,而是一种选择。

  1. 检查输入的字符串以确保它至少有两个字符,如果不是,提示用户。

  2. 使用一个 string.Format 调用减少字符串变量和声明行的数量。

    private void Button1_Click(object sender, EventArgs e)
    {
        const string suffix = "ay";
        string enteredString = textBox1.Text;
    
        //Check the length to make sure it is at least 2
        if(enteredString.Length < 2)
        {
            MessageBox.Show("Please enter at least 2 or more characters");
            return;
        }
    
        //We get here if 2 or more characters were entered.
        //Lets go ahead an process our string
        label2.Text = string.Format("{0}{1}{2}",
            enteredString.Substring(1),
            enteredString.Substring(0,1),
            suffix);
    }
    

编辑 - 我已经将上面的答案编辑为您实际想要的内容,它是 1 的第一个子字符串,它将在第一个字母之后为您提供字符串中的所有内容。基本上,你是说给我从位置 1 或第二个字母开始的字符串。然后,第二个变量告诉我从位置 0 开始且长度仅为 1 个字符的字符串。这基本上只会给你第一个字母。所以,这会给你你想要的。结合检查以确保至少输入了两个字符,您不应该有任何异常(exception)。

希望这对您有所帮助!

关于c# - pig 拉丁语翻译。 C#作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42128563/

相关文章:

c# - 使用 Roslyn 时如何验证方法中的参数类型

c# - Asp.net的AutoEventWireup和反射?

c# - 更新/添加表中的行

visual-studio - 忽略 Visual Studio 中的代码分析规则

c# - 使用互操作将多个单词表添加到单词中

c# - Stylecop 配置文件在哪里?

git - Visual Studio 和 libgit2 Git Commit Error In different 解决方案

c# - 如何为在 Visual Studio 2012 中创建的 Windows 服务创建 EXE 安装文件

c++ - 一条定义规则警告

javascript - 将 MathML 解析为纯数学表达式