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

1 view (last 30 days)
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.

Answers (1)

darova
darova on 25 Mar 2020
Correct way to use logical operators iin your case
  5 Comments
darova
darova on 25 Mar 2020
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

Sign in to comment.

Categories

Find more on Environment and Settings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!