C# 如何为字符串赋值并在for循环中计算
我试图给字符串输入中的每个字符赋值,计算总数,然后在标签上显示输出。下面是我如何使用switch实现它的,但是结果仍然显示为“0”。如何解决此错误? 谢谢代码在C中的单击事件上运行#C# 如何为字符串赋值并在for循环中计算,c#,switch-statement,C#,Switch Statement,我试图给字符串输入中的每个字符赋值,计算总数,然后在标签上显示输出。下面是我如何使用switch实现它的,但是结果仍然显示为“0”。如何解决此错误? 谢谢代码在C中的单击事件上运行# 结合评论作为答案 string passport = "ABC123"; char[] array = passport.ToCharArray(0,6); int total = 0; foreach (char c in array) { switch (c) // You're doing your
结合评论作为答案
string passport = "ABC123";
char[] array = passport.ToCharArray(0,6);
int total = 0;
foreach (char c in array) {
switch (c) // You're doing your switch on passport rather than c. – Loocid
{
case 'A': //Make hardcoded values a type of char(with single quote) otherwise it will not compile. case 'A': – Fabio
total += 1;
break;
case 'B':
total += 2;
break;
case 'C':
total += 3;
break;
case '1':
total += 1;
break;
case '2':
total += 2;
break;
case '3':
total += 3;
break;
}
}
Label1.Text = total.ToString();
您正在打开
passport
而不是c
。操作我的坏。谢谢你指出这一点!将硬编码值设置为char
(带单引号)类型,否则它将无法编译<代码>案例“A”:
string passport = "ABC123";
char[] array = passport.ToCharArray(0,6);
int total = 0;
foreach (char c in array) {
switch (c) // You're doing your switch on passport rather than c. – Loocid
{
case 'A': //Make hardcoded values a type of char(with single quote) otherwise it will not compile. case 'A': – Fabio
total += 1;
break;
case 'B':
total += 2;
break;
case 'C':
total += 3;
break;
case '1':
total += 1;
break;
case '2':
total += 2;
break;
case '3':
total += 3;
break;
}
}
Label1.Text = total.ToString();