0

我正在 MATLAB 中制作一个 GUI,它将接受来自用户的数字输入并相应地进行计算。每当用户输入字母而不是数字时,我希望能够创建一个错误对话框。到目前为止,我有这段代码来显示错误消息:

ed = errordlg('Please enter numbers only','Error'); set(ed, 'WindowStyle', 'modal');uiwait(ed);

这是主要代码的一部分,我想将错误消息集成到:

function roofspace_Callback(hObject, eventdata, handles)
aSpace = str2double(get(hObject,'String')); %This is the user entered value for the roofspace.
set(hObject,'UserData',aSpace);

if aSpace==0 %If aSpace does not have anything then nothing is enabled.
   set(findall(handles.uipanelFunds, '-property', 'enable'), 'enable', 'off');
   set(findall(handles.uipanelPanels, '-property', 'enable'), 'enable', 'off');
   set(findall(handles.uipanelUsage, '-property', 'enable'), 'enable', 'off');
   set(handles.calculate,'enable','off');
   set(hObject,'String','');
else %If aSpace hs a value then this enables the rest of the inputs.
   set(findall(handles.uipanelFunds, '-property', 'enable'), 'enable', 'on');
   set(findall(handles.uipanelPanels, '-property', 'enable'), 'enable', 'on');
   set(findall(handles.uipanelUsage, '-property', 'enable'), 'enable', 'on');
   set(handles.calculate,'enable','on');
      
end

编辑: 总之,我需要弄清楚如何将我的错误消息代码集成到这部分代码中,以便它检查用户是否输入了数字,否则我希望显示错误消息。目前,无论用户输入什么,代码都会显示错误消息。

4

1 回答 1

0

您可以按如下方式检查:

我分成aSpace = str2double(get(hObject,'String'));两个陈述(只是因为它更容易解释):

str = get(hObject,'String');
aSpace = str2double(str);

我能想到两种错误情况:

  1. 输入字符串不是数字。
    示例:str = 'abc'
    aSpace= NaN
    值也可能是Inf-Inf
  2. 字符串是一个复数。
    示例:str = '2 + 3i'
    aSpace= 2.0000 + 3.0000i

使用以下if语句检查是否aSpace不是NaNInf-Inf且不是复数

is_ok = isfinite(aSpace) && isreal(aSpace);

if (~is_ok)
    %Handle error...
end
于 2017-03-06T18:01:01.577 回答