Let users enter anything, save integers, give warning otherwise

1 回表示 (過去 30 日間)
J
J 2011 年 5 月 9 日
I want to let users enter any text into my application. I am using the disp() command for this.
I want the users to be able to enter anything. If they enter an integer I want to save it as a string or integer. If they enter anything else I want to give them a warning.
This code doesn't work. Can you help me fix it?
userVar = disp('Enter an integer: ')
if (isinteger(userVar))
% e.g. Enter an integer: 3
A = [A userVar]
else
% e.g. Enter an integer: 3,4
% e.g. Enter an integer: cha1r
warning('Only integers are accepted.')

採用された回答

Walter Roberson
Walter Roberson 2011 年 5 月 9 日
if mod(UserVar,1) == 0
OR
if UserVar == fix(UserVar)
There are other possibilities, too. Last year in CSSM we listed off at least a dozen different ways.

その他の回答 (1 件)

Matt Fig
Matt Fig 2011 年 5 月 9 日
A = [];
while 1
userVar = input('Enter an integer, (or return to quit): ');
if isempty(userVar)
break
elseif isnumeric(userVar) && fix(userVar)==userVar
A = [A userVar];
else
warning('Only integers are accepted.')
end
end
A % Show what user entered (optional)
%
%
%
EDIT Changed FLOOR to FIX for negative integers, thanks to Walter.
  2 件のコメント
Walter Roberson
Walter Roberson 2011 年 5 月 9 日
floor vs fix wouldn't matter: you don't care which way a value gets rounded as long as the rounded value is not exactly equal to the original value except for integral values.
Matt Fig
Matt Fig 2011 年 5 月 9 日
True, D'oh!

サインインしてコメントする。

カテゴリ

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