【发布时间】:2012-01-25 17:09:18
【问题描述】:
我一直在尝试制作一种方法,让用户可以输入 x 和 y 之间的值。 while 循环确保输入值保持在 x 和 y 之间,如果用户输入无效变量(即当程序需要整数时用户输入“e”),我的 try-catch 应该抛出异常。只要没有输入有效变量,do-while 循环就会循环该方法。
这是我的代码,当我运行它时,除了我尝试输入无效变量(例如,如果我输入 'e' 或 '$')之外,一切都运行良好,然后我的程序只是循环代码“NSLog( @"输入一个介于 %i 和 %i 之间的数字", min, max)" 无限。
#import <Foundation/Foundation.h>
@interface UI : NSObject
{
int a;
int ok;
}
-(int)getInt:(int)min:(int)max;
@end
@implementation UI
-(int) getInt: (int) min: (int) max{
ok = 0;
do {
@try {
NSLog(@"Enter a number between %i and %i: ", min, max);
scanf("%i", &a);
while(a<min || a>max){
NSLog(@"Make sure your number is between %i and %i: ", min, max);
scanf("%i", &a);
}
ok=1;
}
@catch (NSException * e) {
NSLog(@"Error. Re-enter your number");
}
} while (ok=0);
return a;
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
UI *ui = [[UI alloc] init];
NSLog(@"The number you entered is %i", [ui getInt:1 :10]);
[ui release];
[pool drain];
return 0;
}
【问题讨论】:
标签: objective-c try-catch