str in a IF statement, PLEASE HELP
2 次查看(过去 30 天)
显示 更早的评论
Thats what I asked to do.
This is my code so far. But its not working for the str and complex part. Can anyone kindly help me?
p = input('To play the game, enter a shooting angle between -90 and 90 degree: ');
for i = 1 : p
if p(i) <= -90 || p(i) >= 90
disp('Enter a real number between -90 and 90 degree!!!');
break
elseif p(i) == 'str'
disp('Enter a real number between (-90~90) rather than string');
break
elseif p(i) == 'complex'
disp('Enter a real number between (-90~90) rather than any complex number')
break
end
end
0 个评论
采纳的回答
sruthi gundeti
2020-9-12
Hi ,
Try Isstr to detect a string and isreal to detect a real number or complex number
for i = 1 : p
if p(i) <= -90 || p(i) >= 90
disp('Enter a real number between -90 and 90 degree!!!');
break
elseif isstr(p(i))
disp('Enter a real number between (-90~90) rather than string');
break
elseif isreal(p(i))==0
disp('Enter a real number between (-90~90) rather than any complex number')
break
end
end
2 个评论
Adam Danz
2020-9-12
编辑:Adam Danz
2020-9-14
This set of tests is not complete and the loop is incorrect. For example, if the user enters the number 10, why would the loop run 10 times? That's what this loop is doing. If the user enters a negative number, the loop doesn't run at all.
Maybe sruthi intended to write
for i = 1 : numel(p)
but it's still not clear why there needs to be a loop in the first place since the instructions are to enter a single value.
Matlab offers much more robust tests for input validation that can be done in a single line of code.
更多回答(1 个)
Adam Danz
2020-9-12
编辑:Adam Danz
2020-9-12
- Why do you have a loop when the instructions ask for a single value?
- The use of break usually indicates inefficient coding. Again, I don't see a reason to have a for-loop to begin with. Even with the loop. I don't understand why you would break after the first iteration.
- Instead of using conditional statements to confirm that the user entered a valid response, use input validation such as validateattributes (doc).
validateattributes(p,{'numeric'},{'scalar','>=',-90,'<=',90},mfilename,'input')
Test some results
% When p is a string
p = '5';
ERROR:
Expected input to be one of these types:
double, single, uint8, uint16, uint32, uint64, int8, int16, int32, int64
% When p contains more than 1 value
p = [1 2];
ERROR:
Expected input to be a scalar.
% When p is a value out of range
p = -180;
ERROR:
Expected input to be a scalar with value >= -90.
p = 100;
ERROR
Expected input to be a scalar with value <= 90.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!