add error for when input is not integer

5 vues (au cours des 30 derniers jours)
Patrick Rogers
Patrick Rogers le 29 Mar 2023
Modifié(e) : Adam Danz le 29 Mar 2023
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?

Réponses (3)

Image Analyst
Image Analyst le 29 Mar 2023
uiwait(errordlg('Error! You must enter an integer (a numerical digit)'));

Walter Roberson
Walter Roberson le 29 Mar 2023
~isnumeric(value) || mod(value, 1) ~= 0

Adam Danz
Adam Danz le 29 Mar 2023
Modifié(e) : Adam Danz le 29 Mar 2023
> 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.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by