How can I repeat question until valid input is entered?

9 visualizaciones (últimos 30 días)
youruined_everything
youruined_everything el 25 de Nov. de 2016
Comentada: bio lim el 27 de Nov. de 2016
I have a bit of code that asks two questions. I want the questions to continue to be prompted until a valid response is given. For the first question, they need to enter in any number greater than zero. For the second question they must enter in A, B, C, D, or E. Any other response should either repeat the question or potentially rephrase the question to emphasize the correct format. Here is the code that works as long as they enter the response correctly.
%Input
fpc = input('Enter specified compressive strength (psi): ');
Facility = input('Chooose facility letter in upper-case (A-E): ', 's');
And just to show one of the things I've tried:
while Facility ~= 'A,B,C,D,E';
Facility = input('Chooose facility letter in upper-case (A-E): ', 's');
end
And this actually does work, unless the user enters in a value that is more than one character long, then I get a 'matrix dimensions must agree', which doesn't make sense to me. In any case, I'm sure there is a better way to do this.
Thank you

Respuesta aceptada

bio lim
bio lim el 25 de Nov. de 2016
Editada: bio lim el 26 de Nov. de 2016
What if you implement it using a while loop?
%Input
clc;
clear all;
close all;
fpc = input('Enter specified compressive strength (psi): ');
coffee = 0;
while ~coffee
Facility = input('Chooose facility letter in upper-case (A-E): ', 's');
if ~ismember(Facility, {'A','B','C','D','E'})
coffee = 0;
else coffee = 1;
end
end
This will guarantee that the Facility will take a character from A-E, and if not, will continue to loop.
  5 comentarios
youruined_everything
youruined_everything el 26 de Nov. de 2016
Editada: youruined_everything el 27 de Nov. de 2016
Thank you so much. It works perfectly.
bio lim
bio lim el 27 de Nov. de 2016
Glad to help!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Startup and Shutdown en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by