Traping Error user input
    2 次查看(过去 30 天)
  
       显示 更早的评论
    
n=inputdlg('Please input a number more than or equal one:')
I would like to trap the user if they input anything other than numbers more than 1. I have tried loop,isnumeric but they all don't work overally.
Any ideas?
Thank you
0 个评论
采纳的回答
  Honglei Chen
    
      
 2012-4-13
        Is this what you want?
n=inputdlg('Please input a number more than or equal one:')
while isempty(str2num(n{1})) || str2num(n{1})<1
  n=inputdlg('Please input a number more than or equal one:')
end
5 个评论
  Honglei Chen
    
      
 2012-4-15
				n=inputdlg({'Please input a number more than or equal one:';'P'})
while any(cellfun(@isempty,cellfun(@str2num,n,'UniformOutput',false))) || ...
 any(cellfun(@lt,cellfun(@str2num,n,'UniformOutput',false),...
 num2cell(ones(numel(n),1))))
 h = errordlg;
 waitfor(h)
 n=inputdlg({'Please input a number more than or equal one:';'P'})
end
更多回答(1 个)
  Image Analyst
      
      
 2012-4-13
        Try this:
clc;    % Clear the command window.
workspace;  % Make sure the workspace panel is showing.
fontSize = 20;
format compact;
% Initialize flag to keep going or not.
keepGoing = true;
userPrompt = 'Enter a number greater than 1';
defaultValue = 42;
while keepGoing
  % Ask user for a number.
  caUserInput = inputdlg(userPrompt, 'Enter the number',1,{num2str(defaultValue)});
  usersValue = round(str2double(cell2mat(caUserInput)));
  % Check for a valid integer.
  if isnan(usersValue)
    % They didn't enter a number.  
    % They clicked Cancel, or entered a character, symbols, or something else not allowed.
    break;
  end
  % See if it's > 1
  if usersValue > 1
    message = sprintf('Success!\n you entered %f.\n', usersValue);
    keepGoing = false; % Bail out
  else
    message = sprintf('Try again.  You entered %f.\n%s', ...
      usersValue, userPrompt);    
    % Keep going.
  end
  uiwait(msgbox(message));
end
4 个评论
  Image Analyst
      
      
 2012-4-14
				It does not stall. It works fine. I just copied it and ran it again. I was able to enter lots of numbers less than 1 and it kept reprompting the user to enter a number >1. When I finally did enter a number > 1, it exited the while loop. It does exactly what you asked for. If it doesn't, then you must have altered it and broken it.
另请参阅
类别
				在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


