我是编程的新手,我正在尝试创建一种算法,可以决定我想要用葡萄牙语写的东西,或者我想要用英语写的东西。我得到嵌套开关的结构但是我没有如何输入来决定将执行什么开关。对不起,如果这是一个愚蠢的问题,但我是编程新手。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int number, pt=0, en=0, language;
do
{
Console.Clear();
Console.Write("Insert a number from 1 to 5:");
} while (!int.TryParse(Console.ReadLine(), out number) || number < 1 || number > 5);
Console.WriteLine("Do you want to see the number written in English or Portuguese/ (1 or 2)?");
int.TryParse(Console.ReadLine(), out language);
switch (pt)
{
case 1:
Console.WriteLine("um");
break;
case 2:
Console.WriteLine("dois");
break;
case 3:
Console.WriteLine("três");
break;
case 4:
Console.WriteLine("quatro");
break;
case 5:
Console.WriteLine("cinco");
break;
default:
Console.WriteLine("Insira um número de 1 a 5.");
switch (en)
{
case 1:
Console.WriteLine("one");
break;
case 2:
Console.WriteLine("two");
break;
case 3:
Console.WriteLine("three");
break;
case 4:
Console.WriteLine("four");
break;
case 5:
Console.WriteLine("five");
break;
default:
Console.WriteLine("Insert a number from 1 to 5.");
break;
}
break;
}
Console.ReadKey();
}
}
}
答案 0 :(得分:0)
为什么所有这些都是switch
?把字典:
private static Dictionary<int, string> s_Digits_Pt = new Dictionary<int, string>
{1, "um"},
{2, "dois"},
{3, "três"},
{4, "quatro"},
{5, "cinco"},
};
private static Dictionary<int, string> s_Digits_En = new Dictionary<int, string>
{1, "one"},
{2, "two"},
{3, "three"},
{4, "four"},
{5, "five"},
};
拥有此集合,您可以将逻辑设为
...
// Depending on the language required (Portuguese / English)
// choose the right dictionary
Dictionary<int, string> dict = language == 1
? s_Digits_Pt
: s_Digits_En;
if (dict.TryGetValue(number, out var result) // do we have a key (translation)?
Console.WriteLine(result); // yes - put the translation
else
Console.WriteLine(language == 1 // no - complain using the right language
? "Insira um número de 1 a 5."
: "Insert a number from 1 to 5.");
答案 1 :(得分:0)
switch
不是可扩展的解决方案
尝试使用Dictionary
(非常适合翻译)
Dictionary<string, string> enVocabulary = new Dictionary<string, string>
{
{"1", "one"},
{"2", "two"},
{"3", "three"},
{"4", "four"},
{"5", "five"},
};
Dictionary<string, string> ptVocabulary = new Dictionary<string, string>
{
{"1", "um"},
{"2", "dois"},
{"3", "três"},
{"4", "quatro"},
{"5", "cinco"},
};
Console.WriteLine("Do you want to see the number written in English or Portuguese/ (1 or 2)?");
int.TryParse(Console.ReadLine(), out language);
Dictionary<string, string> vocabulary;
if (language == 1)
vocabulary = enVocabulary;
else if (language == 2)
vocabulary = ptVocabulary;
else
{
Console.WriteLine("Unknown language");
return;
}
do
{
Console.Write("Type something: ");
string text = Console.ReadLine();
if (text == "quit") break;
string translation;
if (vocabulary.TryGetValue(text, out translation))
Console.WriteLine(translation);
else
Console.WriteLine("Cannot translate");
}
while (true);