add error for when input is not integer

조회 수: 5 (최근 30일)
Patrick Rogers
Patrick Rogers 2023년 3월 29일
편집: Adam Danz 2023년 3월 29일
strStart = ["first";"second";"third";"fourth";"fifth";...
"sixth";"seventh";"eighth";"ninth";"tenth";"eleventh";"twelfth"];
strVerse = ["A partridge in a Pear Tree";"2 Turtle Doves";"3 French Hens"...
;"4 Colly Birds";"5 Gold Rings";"6 Geese-a-Laying";"7 Swans-a-Swimming";...
"8 Maids-a-Milking";"9 Ladies Dancing";"10 Lords-a-Leaping";...
"11 Pipers Piping";"12 Drummers Drumming";];
value = input ("Please enter value in the range (1-12):");
while( value > 12 || value < 1 )
value = input("Error!, Please enter value in the range (1-12): ");
end
fprintf("\nOn the %s day of Christmas\nMy true love gave to me\n",...
strtrim(strStart(value,1:end)));
while(value ~= 0)
fprintf("%s\n" , strVerse(value,1:end));
value = value - 1;
end
I want to add an error message for when the input is not an integer and idk how. also how do i make it so the solution displays output at the center of the user screen?

답변 (3개)

Image Analyst
Image Analyst 2023년 3월 29일
uiwait(errordlg('Error! You must enter an integer (a numerical digit)'));

Walter Roberson
Walter Roberson 2023년 3월 29일
~isnumeric(value) || mod(value, 1) ~= 0

Adam Danz
Adam Danz 2023년 3월 29일
편집: Adam Danz 2023년 3월 29일
> I want to add an error message for when the input is not an integer
This returns true when the value is an interger mod(value,1)==0
But you should also test that the value is numerica and a scalar.
isscalar(value) && isnumeric(value) && mod(value,1)~=0)
If you want to repeat the input prompt if the users does not enter an expected response, you can wrap the call to input within a while loop. That's demonstrated in this answer.
> how do i make it so the solution displays output at the center of the user screen
You'll have to use a dialog box such as the one Image Analyst suggested or
h=msgbox(__);
movegui(h,'center')
The last line moves the figure to the center of the screen.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by