【问题标题】:Checking For Proper Input of `Edit Text` String检查“编辑文本”字符串的正确输入
【发布时间】:2015-02-16 15:32:42
【问题描述】:

我有一个 GUIDE GUI,我要求用户输入他们的名字。如果他们输入数字字符、字符串和数字字符的混合字符或空白框,它应该执行一个错误对话框。

问题是当我输入数字或字符串和数字字符的混合时,它输出Error Code II(第一个elseif语句)而不是Error Code III(仅输入数字)或Error Code IV (输入数字和字符串)。我们将不胜感激。

这基本上是我所拥有的:

if isempty(editString)
errordlg('Please enter a name into the text-box. We thank you in anticipation.',...
'Error Code I');
return
elseif char(editString) > 12
    errordlg('Please enter a name that is less than 12 characters long. Thank you.',...
 'Error Code II');
    return
elseif isa(editString, 'integer')
    errordlg('Please enter a name, not numbers. Thank you.', 'Error Code III');
    return
elseif isa(editString, 'integer') && isa(editString, 'char')
    errordlg('Please enter a name without mixing numbers & characters. Thanks.',...
    'Error Code IV');
else 
delete(gcf)    
gui_02
end

【问题讨论】:

  • 你是对的。我想我应该把它改成网名而不是真实姓名,以尽量保持它有条件地适应。谢谢亚伦。

标签: string matlab user-interface input matlab-guide


【解决方案1】:

好吧,isa() 函数在这种情况下不起作用,因为您从 Edit Text 读取的所有内容都是 string,换句话说,char。因此,即使你写isa('123', 'integer'),函数返回0 而不是1。无论如何,感谢 MATLAB 有一个函数:isstrprop() 确定字符串是否属于指定类别,例如integerchar..

检查下面的代码:

if isempty(editString)
    errordlg('Please enter a name into the text-box. We thank you in anticipation.', 'Error Code I');
    return
elseif length(editString) > 12
    errordlg('Please enter a name that is less than 12 characters long. Thank you.', 'Error Code II');
    return
elseif ~isempty(find(isstrprop(editString, 'digit'), 1)) & isempty(find(isstrprop(editString, 'alpha'), 1))
    errordlg('Please enter a name, not numbers. Thank you.', 'Error Code III');
    return

elseif ~isempty(find(isstrprop(editString, 'digit'), 1)) & ~isempty(find(isstrprop(editString, 'alpha'), 1))
    errordlg('Please enter a name without mixing numbers & characters. Thanks.', 'Error Code IV');
    return
end

它看起来并不优雅,但很有效。

【讨论】:

  • 我很欣赏您回答的教学方面和对代码的更改。感谢您对这个问题和上一个问题的帮助!
  • @muaaQ - 欢迎您。如果有用,请接受作为答案或投票。
  • 非常好的mehmet,+1,
  • @Kamtal - 谢谢(:如您所见,代码看起来不太好。有没有更好的方法来代替使用函数的嵌套调用:isempty(find(isstrprop(...)))
  • 是的,我看到了,但我想不出更好的办法。没关系!
猜你喜欢
  • 1970-01-01
  • 2014-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-09
  • 1970-01-01
  • 2017-04-28
相关资源
最近更新 更多