add error for when input is not integer

6 ビュー (過去 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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by