add error for when input is not integer

7 visualizzazioni (ultimi 30 giorni)
Patrick Rogers
Patrick Rogers il 29 Mar 2023
Modificato: Adam Danz il 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?

Risposte (3)

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

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

Adam Danz
Adam Danz il 29 Mar 2023
Modificato: Adam Danz il 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.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by