简体   繁体   English

使用 String.ToUpper() 时程序退出; 在一个有空格的字符串上

[英]Program exiting when using String.ToUpper(); on a string that has spaces in it

Let me start off saying that I'm new to C#.首先让我说我是 C# 的新手。

I'm currently in the making of my first command-line application that in it's current state can do two things.我目前正在制作我的第一个命令行应用程序,它在当前状态下可以做两件事。 One of them is a calculator, for which I need more learning to actually make it work, and the other is a string capitalizer.其中一个是计算器,我需要更多的学习才能让它发挥作用,另一个是字符串大写。

I have a string nameCapInput = Console.Readline() that takes in the user input, which then gets analyzed to make sure that no digits are allowed:我有一个string nameCapInput = Console.Readline()接受用户输入,然后对其进行分析以确保不允许使用数字:

using System;
using System.Linq;

namespace First_Console_Project
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("My first ever console application - 2020/2/26\n\n\n");
        programSel:
            Console.WriteLine("What do you want to do?\n");
            Console.WriteLine("1. Calculate Numbers \n2. Capitalize Letters/Strings");
            Console.WriteLine("Input your desired action:");
            var inputVar = Console.ReadLine();
            switch (inputVar)
            {
                case "1":
                    //Calculator code goes here
                    Console.WriteLine("Number 1 succeeded, opening calculator... Stand by");
                    Console.WriteLine("Calulator Loaded.");
                    Console.WriteLine("Doesn't work right now. Type \"exit\" to get back to the \"what do you want to do\" page.");
                    //Code goes here when I have learned the proper methods
                calcInput:
                    var calcInput = Console.ReadLine();
                    if (calcInput == "exit")
                    {
                        goto programSel;
                    } else
                    {
                        Console.WriteLine("Unknown command. Type \"exit\" to get back to the \"what do you want to do\" page.");
                        goto calcInput;
                    }
                case "2":
                    Console.WriteLine("Loading string capitalizer...");
                    Console.WriteLine("Type any string made of letters only without spaces, because if you use spaces, the program will exit. The output will make them all uppercase. Type \"exit\" to get back to the \"what do you want to do\" page.");
                inputCap:
                    string nameCapInput = Console.ReadLine();
                    bool containsInt = nameCapInput.Any(char.IsDigit);
                    bool isMadeOfLettersOnly = nameCapInput.All(char.IsLetter);
                    if (nameCapInput == "exit")
                    {
                        goto programSel;
                    }
                    else if (containsInt)
                    {
                        Console.WriteLine("You can't capitalize numbers. Use letters only. Try again.");
                        goto inputCap;
                    }
                    else if (isMadeOfLettersOnly)
                    {
                        string upper = nameCapInput.ToUpper();
                        Console.WriteLine($"The uppercase version of your entered text is: {upper}");
                        goto inputCap;
                    }
                    break;
                    }
            }
        }
}

Now, everything works fine and it capializes everything I put into it except strings with spaces in them.现在,一切正常,它把我放进去的所有东西都大写了,除了里面有空格的字符串。 When I type in a string with spaces in it, the program just exits with code 0. I'm not very good at C# yet, so I don't really know where to go from here.当我输入一个带有空格的字符串时,程序只是以代码 0 退出。我还不太擅长 C#,所以我真的不知道从哪里开始。 Any help is appreciated.任何帮助表示赞赏。

Every time I learn something new in C#, I try to implement it into my projects, so I can actually learn how to implement it to know when and how to use what I learned.每次我在 C# 中学习新东西时,我都会尝试将它实现到我的项目中,这样我就可以真正学习如何实现它以了解何时以及如何使用我学到的东西。 This is an example for that.这是一个例子。

EDIT: Added the rest of the code.编辑:添加了其余的代码。 Thank you all very much.非常感谢大家。 There's two things I have learned here:我在这里学到了两件事:

  1. goto is a bad habit goto是个坏习惯
  2. I absolutely need to start learning to debug my own code.绝对需要开始学习调试我自己的代码。

Check the documentation: https://docs.microsoft.com/en-us/dotnet/api/system.char.isletter?view=netframework-4.8检查文档: https : //docs.microsoft.com/en-us/dotnet/api/system.char.isletter?view=netframework-4.8

Based on the documentation of the IsLetter function, the space is not included in the return true cases.根据IsLetter函数的文档,该空间不包含在 return true 案例中。

I would suggest that you use regular expressions for this or change your last case to我建议您为此使用正则表达式或将您的最后一个案例更改为

else if (!containsInt)
{
    var upper = nameCapInput.ToUpper();
    Console.WriteLine($"The uppercase version of your entered text is: {upper}");
    goto inputCap;
}

Also check the documentation of goto: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto还要检查 goto 的文档: https : //docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto

The goto statement transfers the program control directly to a labeled statement. goto 语句将程序控制直接转移到带标签的语句。

A common use of goto is to transfer control to a specific switch-case label or the default label in a switch statement. goto 的一个常见用途是将控制转移到特定的 switch-case 标签或 switch 语句中的默认标签。

The goto statement is also useful to get out of deeply nested loops. goto 语句对于摆脱深度嵌套的循环也很有用。

You are not in any such case, so you shouldn't use it.你不是在任何这样的情况下,所以你不应该使用它。

The crux of your problem is that you are only checking if the input contains letters (not spaces).问题的关键是您检查输入是否包含字母(而不是空格)。 An easy fix is to change your LINQ a bit.一个简单的解决方法是稍微改变你的 LINQ。

bool isMadeOfLettersOnly = nameCapInput.All(c => char.IsLetter(c) || char.IsWhiteSpace(c));

So now input with letters or spaces will be considered valid.所以现在输入的字母空格将被认为是有效的。

In addition, your use of goto is a very bad idea.此外,您使用goto是一个非常糟糕的主意。 Generally there should never be any reason to use goto .一般来说,永远不应该有任何理由使用goto

To fix this, use a while loop and a method:要解决此问题,请使用 while 循环和方法:

public static void Main()
{
    bool exit = false;
    do {
        exit = ProcessInput();
    }
    while(!exit);
}

private static bool ProcessInput()
{
    string nameCapInput = Console.ReadLine();

    bool containsInt = nameCapInput.Any(char.IsDigit);
    bool isMadeOfLettersOnly = nameCapInput.All(c => char.IsLetter(c) || char.IsWhiteSpace(c));

    if (nameCapInput.Equals("exit", StringComparison.CurrentCultureIgnoreCase))
    {
        return true; //exiting so return true
    }
    else if (containsInt)
    {
        Console.WriteLine("You can't capitalize numbers. Use letters only. Try again.");
    }
    else if (isMadeOfLettersOnly)
    {
        string upper = nameCapInput.ToUpper();
        Console.WriteLine("The uppercase version of your entered text is: {0}", upper);
    }   
    return false; //no exit, so return false
}

This is just a quick refactor, you could make it better.这只是一个快速重构,你可以让它变得更好。

Fiddle here在这里摆弄

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM