SWITCH expression must be a scalar or a character vector. issue

Hi im trying to calculate price of 1,2,3 or more glass of milk. 1 glass of milk must be 1.75$ 2 is 3.0$ 3 is 3.5$ and for more glass 3.5$ + 0.5+ for every glass, but i am getting this error "SWITCH expression must be a scalar or a character vector". Any idea ? i check forum before but answer i get dont solve my problem thx for any help. Btw my proffesor only accept the homework if i use "inputdlg" "msgbox(sprintf(", and switch case stracture.
box=inputdlg('how many glass of milk');
switch box
case '1'
price=1.75;
case '2'
price=3;
case '3'
price=3.5;
otherwise
price=3.5+(0.5)*x;
end
msgbox(sprintf('you must pay %f',price));

 採用された回答

Alex Mcaulley
Alex Mcaulley 2019 年 3 月 12 日

1 投票

inputdls is returning a cell, and also the variable x is not defined. Then you need to do something like this:
box=inputdlg('how many glass of milk');
switch box{1}
case '1'
price=1.75;
case '2'
price=3;
case '3'
price=3.5;
otherwise
price=3.5+(0.5)*str2double(box{1});
end
msgbox(sprintf('you must pay %f',price));

1 件のコメント

Guillaume
Guillaume 2019 年 3 月 12 日
If you want the code to be robust (remember that user input can be completely different from what you expected), I would do the conversion to double before the switch, then check it is indeed a number and scalar, so:
box = inputdlg('how many glass of milk');
box = str2double(box{1}); %will be nan if box{1} is not a number
assert(~isnan(box) && isscalar(box), 'Invalid input');
switch box
case 1 %no longer a char array
%...
end

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by