while expression specification - problems with error messages
Mostrar comentarios más antiguos
Hello,
is there any (simple) way to set up that an input can contain ONLY values from an interval (not necessarily of integers)?
Something such as:
abc=input('Choose a number from <-1000;999>: ')
while abc<1000||abc>999
abc=input('Wrong! Choose again a number from <-1000;999>: ')
works good, when I answer outside the interval. However, when I answer with a letter or with nothing typed at all - just clicking on enter button, I get these error messages:
??? Error using ==> input
Undefined function or variable '_that letter_'.
or
??? Error: Unexpected MATLAB expression.
for the letters. And:
??? Operands to the || and && operators must be convertible to logical scalar values.
Error in ==> blah at 12
while abc<-1000||abc>999
while no typing an answer at all. I want to make it idiotproof as much as possible.
I guess I am not even taking into account typing more inputs (probably nargin>1; error('... :'?). That could actually sort out the latter, too via nargin<1, right?
Respuesta aceptada
Más respuestas (1)
Azzi Abdelmalek
el 31 de Dic. de 2012
Editada: Azzi Abdelmalek
el 31 de Dic. de 2012
abc=input('Choose a number from <-1000;999>: ')
while abc<-1000 || abc>999
abc=input('Wrong! Choose again a number from <-1000;999>: ')
if isempty(abc) | ~isnumeric(abc)
abc=1000
end
end
4 comentarios
Walter Roberson
el 31 de Dic. de 2012
If you do not include the 's' option for input() then the input is eval()'d. If the user input happens to include a word and that word does not happen to be the name of a variable or function such as pi, then eval() is going to complain about the word being an undefined variable. This is not something you can detect after the fact: the eval() has alredy taken place. So you use the 's' option of input() to receive a string instead.
Azzi Abdelmalek
el 31 de Dic. de 2012
Editada: Azzi Abdelmalek
el 31 de Dic. de 2012
There will be an error message, but the program will not skip the loop. Is there a way to avoid this error message?
Walter Roberson
el 31 de Dic. de 2012
You can use try/catch . But better is to use the 's' option of input() and look at whether you have a number-like-string before you convert the string to numeric.
John
el 4 de En. de 2013
Categorías
Más información sobre Characters and Strings en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!