Как избавиться от goto без вреда для программы? - C#
Формулировка задачи:
Как избавиться от goto, сохранив при этом функционал программы? Чтобы программа работала точно так же как и с goto?
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.Write("Ввод строки: ");
string s = Console.ReadLine();
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine(s[i] + " - ASCII: " + Convert.ToInt32(s[i]));
}
a: Console.WriteLine("\nВыберите систему счисления: 16, 8, 2:");
int q = int.Parse(Console.ReadLine());
if (q == 16)
{
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine("{0} - ASCII: {1} - Шестнадцатеричная система: {2}", s[i], Convert.ToInt32(s[i]), Convert.ToString((int)s[i], 16));
}
goto a;
}
if (q == 8)
{
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine("{0} - ASCII: {1} - Восьмеричная система: {2}", s[i], Convert.ToInt32(s[i]), Convert.ToString((int)s[i], 8));
}
goto a;
}
if (q == 2)
{
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine("{0} - ASCII: {1} - Двоичная система: {2}", s[i], Convert.ToInt32(s[i]), Convert.ToString((int)s[i], 2));
}
goto a;
}
Console.ReadKey();
}
}
}Решение задачи: «Как избавиться от goto без вреда для программы?»
textual
Листинг программы
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Console.Write("Ввод строки: ");
string s = Console.ReadLine();
for (int i = 0; i < s.Length; i++)
Console.WriteLine(s[i] + " - ASCII: " + Convert.ToInt32(s[i]));
Console.WriteLine("\nВыберите систему счисления: 16, 8, 2, exit - выход:");
Dictionary<int, string> numSystems = new Dictionary<int, string> { { 2, "Двоичная" }, { 8, "Восьмеричная" }, { 16, "Шестнадцатеричная" } };
string input;
while ((input = Console.ReadLine()) != "exit")
{
int numSystem;
if (!int.TryParse(input, out numSystem) || !numSystems.ContainsKey(numSystem))
{
Console.WriteLine("Неизвестная система счисления");
continue;
}
string numSystemName = numSystems[numSystem];
for (int i = 0; i < s.Length; i++)
Console.WriteLine("{0} - ASCII: {1} - {2} система: {3}", s[i], Convert.ToInt32(s[i]), numSystemName, Convert.ToString((int)s[i], numSystem));
}
Console.ReadKey();
}
}