Trying to fix the loop

2 次查看(过去 30 天)
Cameron Paterson
Cameron Paterson 2021-11-16
编辑: Jan 2021-11-16
I am trying to change my code so when it loops more than five times the error message changes to Invalid vehicle type! Re-enter vehicle type (Compact, Midsize, Truck, Industrial, Military)
I have been trying to just use the variable n>5 under the for loop for this but keep getting error messages
Vehicle_Type=input('Enter the Vehicle Type','s')
for n=1:5
switch Vehicle_Type
case{'compact','Compact'}
fprintf('1\n');
break
case{'midsize','Midsize'}
fprintf('2\n');
break
case{'truck','Truck'}
fprintf('3\n');
break
case{'industrial','Industrial'}
fprintf('4\n');
break
case{'military','Military'}
fprintf('4\n');
break
otherwise
fprintf('Vehicle type is not recognized. The program stops. Rerun the program again\n')
end
end
  1 个评论
Awais Saeed
Awais Saeed 2021-11-16
what actually are you trying to do? Your loop does not make any sense. Your user input should be inside the loop to ask for the input for all iterations.

请先登录,再进行评论。

采纳的回答

Jan
Jan 2021-11-16
编辑:Jan 2021-11-16
nFail = 0;
for n = 1:5
Vehicle_Type = input('Enter the Vehicle Type', 's');
switch lower(Vehicle_Type)
case 'compact'
fprintf('1\n');
break
case 'midsize'
fprintf('2\n');
break
case 'truck'
fprintf('3\n');
break
case 'industrial'
fprintf('4\n');
break
case 'military'
fprintf('4\n');
break
otherwise
fprintf('Vehicle type is not recognized. The program stops. Rerun the program again\n');
nFail = nFail + 1;
end
end
if nFail == 5
fprintf('bad\n');
end
I'd solve this without a for loop:
found = 0;
nFail = 0;
while ~any(found) && nFail < 5
Vehicle_Type = input('Enter the Vehicle Type', 's');
switch lower(Vehicle_Type)
case 'compact'
found = 1;
case 'midsize'
found = 2;
case 'truck'
found = 3;
case {'industrial', 'military'}
found = 4;
otherwise
fprintf('Vehicle type is not recognized. Again...\n');
nFail = nFail + 1;
end
end
if found
fprintf('%d\n', found);
else
fprintf('failed too often\n');
end

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by