在C# 简单的计算器,我无法理解为什么我得到采取任何的输入类计算器C#提供了一个错误,如果字符串转换成int
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
char choice = '7';
while (choice != '3')
{
Console.WriteLine("---------------Calculator---------------");
Console.WriteLine("\n1.Add\n2.Subtract\n3.Multiply\n4.Divide\n5.Modulo-Operation (remainder)\n6.Exit\n");
Console.WriteLine("Enter your choice:");
choice = Convert.ToChar(Console.Read());
switch (choice)
{
case '1':
Calculator.Add();
break;
case '2':
Calculator.Subtract();
break;
case '3':
Calculator.Multiply();
break;
case '4':
Calculator.Divide();
break;
case '5':
Calculator.Modulo();
break;
case '6':
Environment.Exit(0);
break;
default:
Console.WriteLine("Invalid Choice.\n");
break;
}
}
}
}
class Calculator
{
public static void Add()
{
int a, b;
string sa, sb;
Console.WriteLine("Enter the first number:\n");
sa = Console.ReadLine().Trim();
a = Convert.ToInt32(sa);
Console.WriteLine("Enter the second number:\n");
sb = Console.ReadLine().Trim();
b = Convert.ToInt32(sb);
Console.Write("{0}\n", a + b);
}
public static void Subtract()
{
int a, b;
string sa, sb;
Console.WriteLine("Enter the first number:\n");
sa = Console.ReadLine().Trim();
a = Convert.ToInt32(sa);
Console.WriteLine("Enter the second number:\n");
sb = Console.ReadLine().Trim();
b = Convert.ToInt32(sb);
Console.Write("{0}\n", a - b);
}
public static void Multiply()
{
int a, b;
string sa, sb;
Console.WriteLine("Enter the first number:\n");
sa = Console.ReadLine().Trim();
a = Convert.ToInt32(sa);
Console.WriteLine("Enter the second number:\n");
sb = Console.ReadLine().Trim();
b = Convert.ToInt32(sb);
Console.Write("{0}\n", a * b);
}
public static void Divide()
{
int a, b;
string sa,sb;
Console.WriteLine("Enter the first number:\n");
sa = Console.ReadLine().Trim();
a = Convert.ToInt32(sa);
Console.WriteLine("Enter the second number:\n");
sb = Console.ReadLine().Trim();
b = Convert.ToInt32(sb);
while (b == 0)
{
Console.WriteLine("In division operation, divisor cannot be zero.\n Retry!!\n");
Console.WriteLine("Enter the second number:\n");
sb = Console.ReadLine().Trim();
b = Convert.ToInt32(sb);
}
Console.Write("{0}\n", a/b);
}
public static void Modulo()
{
int a, b;
string sa, sb;
Console.WriteLine("Enter the first number:\n");
sa = Console.ReadLine().Trim();
a = Convert.ToInt32(sa);
while (a < 0)
{
Console.WriteLine("In modulo operation, first number cannot be negative.\n Retry!!\n");
Console.WriteLine("Enter the second number:\n");
sb = Console.ReadLine().Trim();
b = Convert.ToInt32(sb);
}
Console.WriteLine("Enter the second number:\n");
sb = Console.ReadLine().Trim();
b = Convert.ToInt32(sb);
Console.Write("{0}\n", a % b);
}
}
}
例外,我总是得到一个错误,如“出现FormatException:”错误将字符串转换为DateTime
请熬下来到[MCVE。另外,你想要转换为日期时间的具体字符串是什么? –
如果您提供行号异常的行号,可以更快得到答案 – Fabio
粘贴确切的异常。在这段代码中,你没有使用'DateTime',所以你不能将_error转换字符串转换为DateTime_ – Pikoh