我正在尝试检查用户是否提供了数字而非字母的输入。当给出非数字值时,我想打印一条警告错误消息,如“格式不正确”。
这是我的源代码:
-(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];
}
答案 0 :(得分:4)
使用NSNumberFormatter。如果输入参数不是有效数字,则导出的数字将为nil。
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
num1 = [f numberFromString:firstString];
[f release];
if (num1 == nil) {
// throw exception
}
答案 1 :(得分:0)
我就是这样做的:
NSCharacterSet *nonNumbers = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([firstString rangeOfCharacterFromSet:nonNumbers].location != NSNotFound) {
// firstString has non-number characters in it!
}