【发布时间】:2020-02-27 17:59:08
【问题描述】:
首先让我说我是 C# 新手。
我目前正在制作我的第一个命令行应用程序,它在当前状态下可以做两件事。其中一个是计算器,我需要更多的学习才能真正让它工作,另一个是字符串大写字母。
我有一个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;
}
}
}
}
现在,一切正常,它将我放入其中的所有内容都大写除了字符串,其中包含空格。当我输入一个带有空格的字符串时,程序会以代码 0 退出。我还不太擅长 C#,所以我真的不知道从这里往哪里走。任何帮助表示赞赏。
每次我在 C# 中学习新东西时,我都会尝试将其实施到我的项目中,这样我就可以真正学习如何实施它,以了解何时以及如何使用我所学的内容。这是一个例子。
编辑:添加了其余代码。 非常感谢大家。我在这里学到了两件事:
-
goto是个坏习惯 - 我绝对需要开始学习调试我自己的代码。
【问题讨论】:
-
首先,完全停止使用
goto。这不是 1980 年代。 -
使用
goto是你需要马上改掉的习惯。 -
当你有一个空间时 isMadeOfLettersOnly 将是假的。您没有显示完整的程序,所以我们不知道如果执行超出显示的末尾会发生什么。
-
重复一遍,去掉
goto -
哇,你们很多人都说
goto不好。那我应该用什么?
标签: c# command-line .net-core-3.1