Prompting Error for user input

2 ビュー (過去 30 日間)
T
T 2013 年 2 月 14 日
Suppose I have a input box that requires an entry greater than zero before attempting to load a file.
function test_Callback(hObject, eventdata, handles)
test = str2double(get(hObject, 'String'));
if isnan(test)
set(hObject, 'String', 0);
errordlg('Input must be a number','Error');
end
handles.backup.test= test;
guidata(hObject,handles)
function loaddata_Callback(hObject, eventdata, handles)
test_Callback(hObject, eventdata, handles)
[filename, pathname, Index] = ...
uigetfile({'*.txt';},['Select the File to load'],...
'\\MyDocuments\User');
This prompts the error "'Input must be a number','Error'' and allows the user to open and search for this file. What am I doing wrong?
  6 件のコメント
per isakson
per isakson 2013 年 2 月 19 日
編集済み: per isakson 2013 年 2 月 20 日
Yes, but what does the code that I added to my answer do?
per isakson
per isakson 2013 年 2 月 20 日
Change
for ii = 1 : 10
to
while true

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

採用された回答

per isakson
per isakson 2013 年 2 月 14 日
編集済み: per isakson 2013 年 2 月 19 日
You need to put this
test = str2double(get(hObject, 'String'));
if isnan(test)
set(hObject, 'String', 0);
errordlg('Input must be a number','Error');
end
in a loop and not leave the loop until you have a legal value from the user.
BTW: I think it is a good habit to close functions with "end".
.
A detail: change
set(hObject, 'String', 0);
to
set(hObject, 'String', '0' );
.
An example according to my originally answer. This code gives the user ten chances to enter a correct value.
function test_Callback(hObject, eventdata, handles)
for ii = 1 : 10
test = str2double(get(hObject, 'String'));
if isnan(test)
set(hObject, 'String', 0);
errordlg('Input must be a number','Error');
elseif gt(test,1)
handles.backup.test = test;
guidata(hObject,handles);
break
elseif gt(1,test)
set(hObject, 'String', '0');
errordlg('Input must be greater than 0','Error');
end
end
end
  3 件のコメント
per isakson
per isakson 2013 年 2 月 20 日
How do you want the program to behave?
per isakson
per isakson 2013 年 2 月 21 日
  • one way would be to make errordlg non-modal and hope that the user sets a legal before before responding to errordlg - might confuse the user (not tested)
  • a better way would be to let test_Callback return a logical value is_ok and
if is_ok
[filename, pathname, Index] = ...
uigetfile({'*.txt';},['Select the File to load'],...
'\\MyDocuments\User');
else
some_dialog('enter a positive integer and try again')
end

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeApp Building についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by