How can I use a 'While Loop' to verify user input where it restricts specific inputs?

1 次查看(过去 30 天)
Hi Everyone!
I'm somewhat new to Matlab - a little trail and error phase.
I've been trying to use a 'While Loop' to verify an input. This issue may seem quite easy to most, but it's been playing
with my head for so long!
Here's the given situation; I just want to check when a user enters an input - there's should be a restriction, also a msg pop-up reassuring them to try again.
Here's my examples below for TWO different text input:
1. function percentageinput_Callback(~, ~, ~)
inputnum=input ('Enter a percentage from 0-100: ');
while inputnum>0% && <=100%
fprintf('You entered a %d. |n|n, inputnum)
inputnum=input ('Enter a percentage from 0%-100%:');
end
For the above secenrio, as you may tell I want the user to only enter a percentage from 0% - 100% - also showing the
percentage sign.
2. function markinput_Callback(~, ~, ~)
inputnum=input ('Enter a makr from 0-100: ');
while inputnum>0 && <=100
fprintf('You entered a %d. |n|n, inputnum)
inputnum=input ('Enter a mark from 0-100:');
end
For the above, the same rule applies but I want to restrict the user from entering character/string and negative number.
Any help will be appreciated!
Thank you.

回答(1 个)

darova
darova 2020-3-25
Correct way to use logical operators iin your case
  5 个评论
darova
darova 2020-3-25
try this
function in1_Callback(~, ~, ~)
str = get (handled.in1,'string');
inputnum = str2double(str);
if inputnum <0 || inputnum >100
s = sprintf('You entered a %d.\nPlease Enter 0 .. 100', inputnum);
msgbox(s)
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by