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

4 ビュー (過去 30 日間)
Miss B
Miss B 2020 年 3 月 25 日
コメント済み: darova 2020 年 3 月 25 日
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
darova
darova 2020 年 3 月 25 日
Can you attach the whoel your project?

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

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by