C# 控制台(输入字符串格式不正确)
嗨,伙计们,我开始学习C#了,当我试图把事情搞混的时候,我遇到了这个问题 它说“输入字符串的格式不正确” n=Convert.ToInt32(Console.ReadLine()) 这是全部代码C# 控制台(输入字符串格式不正确),c#,C#,嗨,伙计们,我开始学习C#了,当我试图把事情搞混的时候,我遇到了这个问题 它说“输入字符串的格式不正确” n=Convert.ToInt32(Console.ReadLine()) 这是全部代码 namespace Exercise13 { class Program { static void Main(string[] args) { char choice; Console.Write("Wha
namespace Exercise13
{
class Program
{
static void Main(string[] args)
{
char choice;
Console.Write("What operation would you like to use?");
Console.WriteLine("\na. Addition \tb. Subtraction \tc.Multiplication \td.Division");
choice = (char)Console.Read();
if (choice == 'a')
{
sumValues();
}
else if (choice == 'b')
{
minusValues();
}
else if (choice == 'c')
{
timesValues();
}
Console.ReadLine();
}
static void sumValues()
{
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
n = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < n; i++)
{
Console.Write("\nInput number: ");
val = Convert.ToInt32(Console.ReadLine());
sum += val;
}
Console.Write("\nThe Answer is: "+sum);
}
static void minusValues()
{
int diff = 0, m, z, value;
Console.Write("How many numbers do you want calculate: ");
m = int.Parse(Console.ReadLine());
for (z = 0; z < m; z++)
{
Console.Write("\nInput number: ");
value = int.Parse(Console.ReadLine());
diff -= value;
}
Console.Write("\nThe Answer is: " + diff);
}
static void timesValues()
{
int prod = 0, e, i, val;
Console.Write("How many numbers do you want to calculate: ");
e = Convert.ToInt32(Console.ReadLine());
for (i = 0; i < e; i++)
{
Console.Write("\nInput number: ");
val = int.Parse(Console.ReadLine());
prod *= val;
}
Console.Write("\nThe answer is: " + prod);
}
}
}
名称空间练习13
{
班级计划
{
静态void Main(字符串[]参数)
{
字符选择;
编写(“您希望使用什么操作?”);
Console.WriteLine(“\na.加法\tb.减法\tc.乘法\td.除法”);
choice=(char)Console.Read();
如果(选项=='a')
{
sumValues();
}
else if(选项==“b”)
{
minusValues();
}
else if(选项=='c')
{
时间值();
}
Console.ReadLine();
}
静态值()
{
int n=0;
整数和=0;
int i=0,val=0;
控制台。写下(“你想计算多少个数字:”);
n=Convert.ToInt32(Console.ReadLine());
对于(i=0;i
使用Integer.TryParse处理可能不是数字的字符串。如果输入不可解析,则提示用户输入有效输入
如果字符串不是一个精确的数字,Convert和Parse都将抛出异常
例外情况非常明显:传递给
Convert
类的字符串的格式对于要返回的类型无效(本例中为int
)。输入一个有效的整数作为字符串,它就会起作用。我刚才输入了1。我尝试了你的所有答案。所有答案都很好。我根据你的3个答案保存了3个文件,以备将来参考:)想法是正确的,但代码是错误的。稍微注意一些细节,比如方法签名和c#语法,这将是一个很好的答案。它现在可以编译了,下次如果你知道下一次出了什么问题,建议你修改。它是写在手机上的,所以我在显示伪代码。抱歉,语法有点不对劲,我已经向上投票以平衡-1的分数,因为它现在确实编译:-)删除了向下投票,但是@ZoharPeled+10对-2不是一个非常平衡的操作。“如果我们只有一种方式来通知其他下层选民,那就更好了。”史蒂夫,我同意这并不是真正平衡声誉点,但它确实平衡了岗位得分。我不会撤回我的投票,因为a。它目前是一个有效的解决方案,b。我必须再次编辑它才能收回。从各方面考虑,我认为这是公平的。
int n = 0;
int sum = 0;
int i = 0,val = 0;
Console.Write("How many numbers do you want calculate: ");
var isValidNumber = Int32.TryParse(Console.ReadLine(), out n);
if(!isValidNumber) {
Console.WriteLine("Invalid number entered!");
}
else {
//Use the number
}