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;
}
}
我的計劃
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();
}
}
我局級
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;
}
}
}
這通常被稱爲「驗證」。 –
不要這樣做 - 讓用戶輸入帶有附加字符的數字,例如空格,逗號,+, - ,然後根據驗證結果過濾輸入或拒絕輸入。即+1,000, - 1 000,1e3,0.1e + 4都可以,1j34不是。 –
謝謝約翰澄清它是「驗證」,以及確認我需要採取不良的輸入,並通知用戶它是壞的。 (我會贊成,但有1名聲望)。 – vayden12