【问题标题】:How do you make a "getInt" method using try-catch and a do-while loop?如何使用 try-catch 和 do-while 循环创建“getInt”方法?
【发布时间】: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


    【解决方案1】:

    您实际上没有任何引发异常的代码,因此没有引发异常也就不足为奇了。要抛出异常,您可以使用@throw。

    但是,这不是你应该这样做的方式。 Objective-C 中的异常几乎总是为不可恢复的编程错误保留,不是不正确的用户输入。您不应该对正常的控制流使用异常。

    【讨论】:

      【解决方案2】:

      scanf 是一个 C 库函数,它不会抛出 Objective-C 异常。您需要检查scanf的返回值,它返回成功解析的项目数,因此如果输入整数,则为1。

      一般来说,您不应该在 Objective-C 中为这种情况使用异常 - 它们是为 exception 问题保留的,而不是这样的错误输入。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-09
        • 1970-01-01
        • 2016-03-21
        相关资源
        最近更新 更多