检查输入值

发布于 2024-12-26 03:48:37 字数 530 浏览 1 评论 0原文

我正在尝试检查用户是否输入了数字而不是字母。当给出非数字值时,我想打印一条警报错误消息,例如“格式不正确”。

这是我的源代码:

-(IBAction)btnPressed{

    NSString *firstString = textFiled1.text;
    NSString *secondString = textFiled2.text;
    NSString *thirdString = textFiled3.text;

    int num1;
    int num2;
    int num3;

    int output;

    num1 = [firstString intValue];
    num2 = [secondString intValue];
    num3 = [thirdString intValue];

    output = (num1 + num2) / num3;

    lable1.text = [NSString stringWithFormat:@"%d",output];
}

I am trying to check whether the user gives an input that is number but not letters. When a non-numeric value is given I want to print an alert error message like "incorrect format".

This is my source code:

-(IBAction)btnPressed{

    NSString *firstString = textFiled1.text;
    NSString *secondString = textFiled2.text;
    NSString *thirdString = textFiled3.text;

    int num1;
    int num2;
    int num3;

    int output;

    num1 = [firstString intValue];
    num2 = [secondString intValue];
    num3 = [thirdString intValue];

    output = (num1 + num2) / num3;

    lable1.text = [NSString stringWithFormat:@"%d",output];
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

非要怀念 2025-01-02 03:48:37

使用 NSNumberFormatter。如果输入参数不是有效数字,则导出的数字将为 nil。

NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
num1 = [f numberFromString:firstString];
[f release];

if (num1 == nil) {
// throw exception
}

Use NSNumberFormatter. If the input parameter is not a valid number, the number derived will be nil.

NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
num1 = [f numberFromString:firstString];
[f release];

if (num1 == nil) {
// throw exception
}
怪我鬧 2025-01-02 03:48:37

我就是这样做的:

NSCharacterSet *nonNumbers = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([firstString rangeOfCharacterFromSet:nonNumbers].location != NSNotFound) {
    // firstString has non-number characters in it!
}

This is how I would do it:

NSCharacterSet *nonNumbers = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([firstString rangeOfCharacterFromSet:nonNumbers].location != NSNotFound) {
    // firstString has non-number characters in it!
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文