2014-12-22 38 views
-1

我在练习c#的数组。我做到了这一点,但遗憾的是最终它并不奏效。我想有这样的:将字符串转换为数组以供数组使用?

例如,用户键入“第三”。我希望它在int中被转换为“2”,所以电脑会选取第三个输入的数字。正如我编写它,它现在崩溃。

Console.WriteLine("Please enter 5 numbers of choice."); 
Int32[] Names = new Int32[5]; 

Names[0] = Convert.ToInt32(Console.ReadLine()); 
Names[1] = Convert.ToInt32(Console.ReadLine()); 
Names[2] = Convert.ToInt32(Console.ReadLine()); 
Names[3] = Convert.ToInt32(Console.ReadLine()); 
Names[4] = Convert.ToInt32(Console.ReadLine()); 

Console.WriteLine("The number you typed third is " + Names[2]); 
Console.Clear(); 

Console.WriteLine("Which number would you like the computer to remember? first, second, third etc."); 


int Choice = Convert.ToInt32(Console.ReadLine()); 
string ChosenNumber = (Console.ReadLine()); 
int first = 0; 
int second = 1; 
int third = 2; 
int fourth = 3; 
int fifth = 4; 
Console.ReadKey(); 
+2

“它不在最后工作”< - 什么不工作?请具体说明。你期望的输入/输出是什么?你的程序产生了什么? – Neolisk

+0

当您输入int的值时,它崩溃了选择= Convert.ToInt32(Console.ReadLine());当你输入一个字符串值并且它不能被转换为int。然而我希望我的程序自动将字符串“third”转换为int“2”。希望我现在解释清楚 –

+0

您可以使用枚举列表或字典进行转换 – Carl

回答

1

最快的解决方案可能会增加一个switch语句来测试用户输入

Console.WriteLine("Which item to view"); 

switch(Console.ReadLine().ToLower()) 
{ 
    case "first": 
     Console.WriteLine(Names[0]); 
     break; 
    case "second": 
     //etc 

    default: 
     Console.WriteLine("Not a valid entry"); 
     break; 
} 
+0

最好重构为一个翻译函数,它将“third”翻译为2,然后将其用于“Console.WriteLine()”。 – Neolisk

1

此行不起作用:

int Choice = Convert.ToInt32(Console.ReadLine()); 

为什么?由于.NET不会将first转换为1。只需"1"1

试试这个:

string input = Console.ReadLine(); 

// create an array of keywords 
string[] choices = new string[] { "first", "second", "third" }; 

// get the index of the choice 
int choice = -1; 
for (int i = 0; i < choices.Length; i++) 
{ 
    // match case insensitive 
    if (string.Equals(choices[i], input, StringComparison.OrdinalIgnoreCase)) 
    { 
     choice = i; // set the index if we found a match 
     break; // don't look any further 
    } 
} 

// check for invalid input 
if (choice == -1) 
{ 
    // invalid input; 
} 
0

假设这个失败:int Choice = Convert.ToInt32(Console.ReadLine()),因为用户输入third,但该字符串不能被解析到一个数值,您既可以使用switch语句,并把它作为一个案例或者有一个Dictionary<string, int>的字符串和它们各自的编号:["FIRST", 1],["SECOND", 2]等等。然后,你可以这样做:int chosenValue = Dictionary[Console.ReadLine().ToUpper()];

0

它崩溃,在这条线

int Choice = Convert.ToInt32(Console.ReadLine()); 

这是因为从string转换为int不会对自然语言的话工作。它适用于string类型。因此,例如,您可以将字符串"3"转换为整数3。但是,对于单词"three",您将无法做到这一点。

在你的情况下,最明显而又乏味的解决方案是制作一个巨大的字典,将string s映射到int s。

var myMappings = new Dictionary<string, int> 
{ 
    { "first", 0 }, 
    { "second", 1 }, 
    { "third", 2 }, 
    { "fourth", 3 }, 
    { "fifth", 4 }, 
} 

然后您搜索词典中的用户输入。

var input = Console.ReadLine(); 
var result = myMappings[input]; // safer option is to check if the dictionary contains the key 

但它不是最优雅的解决方案。而不是一个蛮力。虽然在你的情况下,五件事情并不难。

其他选择,如果您允许更大的选择,唯一合理的选择是尝试“猜测”正确的值。你需要解析字符串并创建一个算法,如果字符串包含单词“twenty”和单词“three”或“third”,那么它是23.我将为你实现这个想法。