【问题标题】:Objective-C: How to return to beginning of application after switch statement is completeObjective-C:switch语句完成后如何返回应用程序的开头
【发布时间】:2011-03-17 07:07:48
【问题描述】:

例如,

在您的程序中,您有:

NSLog(@"Where are you going?");
NSLog(@" 1 = Location1, 2 = Location2");

printf("Make a selection:");

scanf("%i, &value);

switch (value) {
    case 1:
        NSLog(@"You are going to Location 1.")
        break;

    case 2:
        NSLog(@"You are going to Location 2.");
        break;

    default:
        NSLog(@"That is not a valid location");
        break;
}

通常在您输入整数后,您的程序将返回 0 并且应用程序结束。你如何让它“循环”回到原来的 printf 以做出新的选择。或者更好的是,一个新的 printf IE 'printf("你还想去哪里?:");'?

【问题讨论】:

    标签: objective-c xcode ios loops switch-statement


    【解决方案1】:

    你为什么不把它作为一个单独的方法,当你想循环时从它自己调用它。只需考虑以下代码,

    void takeMeToPlaces() {
    
        NSLog(@"Where are you going?");
        NSLog(@"0 = Exit, 1 = Location1, 2 = Location2");
    
        printf("Make a selection:");
    
        scanf("%i, &value);
    
        switch (value) {
            case 0:
                NSLog(@"You don't like to go anywhere");
                break;
    
            case 1:
                NSLog(@"You are going to Location 1.");
                takeMeToPlaces();
                break;
    
            case 2:
                NSLog(@"You are going to Location 2.");
                takeMeToPlaces();
                break;
    
            default:
                NSLog(@"That is not a valid location");
                takeMeToPlaces();
                break;
        }
    }
    

    【讨论】:

    • 这样你可能会垃圾函数的调用堆栈。最好使用简单的for(;;){} 循环(例如)
    猜你喜欢
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 2014-12-09
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 2020-12-22
    相关资源
    最近更新 更多