0 c# validation
全新的C#[4小时新:)],但希望有一些关于Board Feet Calculator的指针,将用户输入仅限制为数字,不允许使用字母或特殊字符.
首先,限制是在类,方法和/或程序中进行的吗?(我相信课程和方法)
其次,我在下面看到了一个例子,我会使用类似的东西吗?
第三,如果是这样,我是否需要为KeyPress和KeyPressEventArgs创建单独的类?(我相信他们自动在那里,例如
public char KeyChar { get; set; }
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
// allows only letters
if (!char.IsLetter(e.KeyChar))
{
e.Handled = true;
}
}
Run Code Online (Sandbox Code Playgroud)
我的计划
namespace BoardFt_MyTry_
{
class Program
{
static void Main(string[] args)
{
Board board = new Board();
board.lengthOfboard = Convert.ToDouble(askQuestion("What is the length of your board in inches?"));
board.widthOfboard = Convert.ToDouble(askQuestion("What is the width of your board in inches?"));
board.thicknessOfboard = Convert.ToDouble(askQuestion("What is the thickness of your board in inches?"));
Console.WriteLine("Your board has {0} board feet.", board.CalcBoardFt());
Console.ReadLine();
}
private static string askQuestion(string question)
{
Console.WriteLine(question);
return Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
我的董事会成员
namespace BoardFt_MyTry_
{
class Board
{
public double lengthOfboard;
public double widthOfboard;
public double thicknessOfboard;
public double CalcBoardFt()
{
double boardft = 0;
boardft = (this.lengthOfboard * this.widthOfboard * this.thicknessOfboard) / 144;
return boardft;
}
}
}
Run Code Online (Sandbox Code Playgroud)
你不能在控制台应用程序中真正做到这一点.您所能做的就是允许用户输入错误数据,然后告诉用户数据不好.
你可以尝试这样的事情:
class Program
{
public double AskDnoubleQuestion(string message){
do {
Console.Write(message);
var input = Console.ReadLine();
if (String.IsNullOrEmpty(input)){
Console.WriteLine("Input is required");
continue;
}
double result;
if (!double.TryParse(input, out result)){
Console.WriteLine("Invalid input - must be a valid double");
continue;
}
return result;
}
static void Main(string[] args)
{
Board board = new Board();
board.lengthOfboard = AskDoubleQuestion("What is the length of your board in inches?");
board.widthOfboard = AskDoubleQuestion(askQuestion("What is the width of your board in inches?");
board.thicknessOfboard = AskDoubleQuestion(askQuestion("What is the thickness of your board in inches?");
Console.WriteLine("Your board has {0} board feet.", board.CalcBoardFt());
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1134 次 |
| 最近记录: |