while condition to test numeric

2 ビュー (過去 30 日間)
Duc-Minh Pham
Duc-Minh Pham 2017 年 8 月 18 日
編集済み: Stephen23 2017 年 8 月 18 日
Hi all!
I want the user to enter a number between 35 and 45, and if they enter anything other than a number to ask them to enter it again. If the input is not numeric, I want the while loop to start again in order to ask the user to enter the value again.
As you can see from my script below, it doesn't work! If they enter "35 hahah", the code ends with an error message. If they enter "haha", there is a red error message but the code does ask them to enter it again. How can I fix this so that there are no error messages?
Thanks in advance.
gearRatio = 10;
rotSpeed = 200;
pressAngle = 20;
powerInput = 0;
while powerInput < 35 || powerInput > 45
powerInput = input('Please enter the power input as a number only, between 35kW and 45kW: ');
if ~isnumeric(powerInput)
break;
end
end

回答 (2 件)

Guillaume
Guillaume 2017 年 8 月 18 日
編集済み: Guillaume 2017 年 8 月 18 日
Carefuly, read the documentation of input. In particular:
  • If the user enters an invalid expression at the prompt, then MATLAB® displays the relevant error message, and then redisplays the prompt.
In other words, if what the user enters something that is not convertible to a matrix, input returns an error. If the user enters something that is convertible to a matrix, then it is always numeric, so your isnumeric text is redundant.
A bit further down in the documentation, you have:
str = input(prompt,'s') returns the entered text, without evaluating the input as an expression.
Therefore, to get the raw text entered use the 's' option. However, you also need to read the documentation of isnumeric as it doesn't test if a string can be converted to number. You could use isstrprop instead.
  1 件のコメント
Stephen23
Stephen23 2017 年 8 月 18 日
編集済み: Stephen23 2017 年 8 月 18 日
+1 Reading the documentation is always a good idea.
Also str2double might be useful.

サインインしてコメントする。


KL
KL 2017 年 8 月 18 日
編集済み: KL 2017 年 8 月 18 日
t = 1;
while t
powerInput = input('Please enter the power input, number only and between 35kW and 45kW: ');
if(powerInput>35 && powerInput<45 && isnumeric(powerInput))
t = 0;
end
disp(powerInput) %yourcalc
end

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by