Domanda

Note: I am programming in Matlab, but this is a general question so presumably any pseudocode should answer my question. I would like to know, how can I go back to a previous block of an if-statement, depending on the results of subsequent if-statements?

Here is my motivation: I have a program that makes a new folder to write to, and if that folder exists already I want the program to ask first before overwriting it. If the users says yes the folder is overwritten, if they say no the program terminates without overwriting. If the user says something other than yes or no, I want go back to the control block that asks whether to overwrite or not. Otherwise, if the user makes a mistake at the yes/no section they have to run the program all over again in order to save their work. This backwards control flow would be easy to implement in a for-loop with a continue-statement, but continue-statements are not valid within an if-statement.

Here is some example code of what I have now:

 confirm = input('Warning: That filepath already exists! Continuing may overwrite 
data saved there. Continue(Y/N)?', 's');

        if strcmpi(confirm, 'Y')                        %Compare to Y, case insensitive
        elseif strcmpi(confirm,'N')                 %Compare to N, case insensitive
                display('Program terminated without saving data');
                return;
        else
               display('Error: Enter Y or N');         %User error, end program        
               return;
        end

If they enter Y (or y) the loop does nothing, if they enter N (or n) the program ends, if they enter anything else they get an error and the program also ends. Instead of ending, I want to go back to the input step and redefine 'confirm'. Is it possible to "rewind" or break from if-statements like this?

È stato utile?

Soluzione

No need for anything fancy:

confirm = input('Warning: That filepath already exists! Continuing may overwrite
data saved there. Continue(Y/N)?', 's');
inputY = 0; % False to start 
inputN = 0;
while ~inputY && ~inputN
    inputN = strcmpi(confirm, 'N');
    if (inputN) 
        display('Program terminated without saving data');
        return;
    end

    inputY = strcmpi(confirm, 'Y');
    if (inputY)
        % Do whatever

    end

    confirm = input('Please enter (Y/N)', 's');
end
enter code here
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top