2017-03-06 84 views
0

我正在MATLAB中製作一個GUI,它將接受來自用戶的數字輸入並相應地進行計算。我希望能夠在用戶輸入字母而不是數字時創建錯誤對話框。到目前爲止,我有這段代碼顯示錯誤消息: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

編輯: 總之,我需要弄清楚如何將我的錯誤消息的代碼集成到這部分代碼,以便它檢查,如果用戶已輸入數字,否則我想顯示一條錯誤消息。目前,無論用戶輸入什麼內容,代碼都會顯示錯誤消息。

+1

有些洞察...什麼?你的問題是什麼? – excaza

+0

@excaza,當用戶給出非數字輸入時,如何獲得此代碼以顯示錯誤消息?就目前而言,無論輸入什麼內容,都會顯示錯誤消息。我不知道如何將錯誤消息代碼集成到程序中以完成此操作 – Oreomega

+0

好像你更關注如何檢查用戶輸入是否是一個數字,而不是在哪裏嵌套if循環。 (如果它確實是你的代碼,我相信你知道把if語句放在哪裏..)。 – BillBokeey

回答

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語句來檢查,如果aSpaceNaN的天道酬勤-Inf,而不是複雜號:

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

if (~is_ok) 
    %Handle error... 
end