Saturday, 7 December 2019

Write a program that will collect one positive integer from the user. Validation is required.

Q:
MATLAB Help:
Write a program that will collect one positive integer from the user. Validation is required. Specifications:
1. The program should collect the input as a string and convert it to a numeric number
2. The program will check if the user enters nothing, a non-numeric value, or not a positive integer. It will keep prompting until the user enters a positive integer.
3. Design a prompt/feedback
Functions you may need: isempty(), isnan(), length(), str2double(), str2num()

Solution:


k=1;
while k==1
    k=0;
    num=input('Enter number: ','s');
    if isempty(num)
        k=1;
        fprintf('you did not enter anything\n')
    elseif isnan(str2double(num))
        k=1;
        fprintf('You entered a non numeric value\n')
    elseif str2double(num)<0
        k=1;
        fprintf('Please enter a positive value\n')
    else
        num=str2double(num);
    end
end
fprintf('You entered :%i\n',num)

No comments:

Post a Comment