Keep prompting user instead of hitting run each time.

1 view (last 30 days)
I would like this code to run in a loop that displays the cost of the package, then loops back to the beginning to prompt the user again to enter a weight (as opposed to me having to run the code each time I want the prompt). I'm sure it's really simple, I've tried putting in a return statement in the code and tried a while loop but I don't know.
weight=0;
weight=input('Input a weight');
if weight<=2
cost=15;
disp(cost);
elseif weight<= 70
cost=(15+((weight-2)*5));
disp(cost);
elseif weight <= 100
cost= (30+((weight-2)*5));
disp(cost);
else
disp('No Weight over 100');
end

Answers (2)

Rik
Rik on 30 Oct 2018
You can wrap your code in a while loop, but that will force the user to hard-break out of your code (ctrl-C on Windows). A nicer solution is to provide the user with the option of exiting.
while true
weight=input('Input a weight (enter negative to exit)');
if weight<0
break
end
if weight<=2
cost=15;
disp(cost);
elseif weight<= 70
cost=(15+((weight-2)*5));
disp(cost);
elseif weight <= 100
cost= (30+((weight-2)*5));
disp(cost);
else
disp('No Weight over 100');
end
end

Walter Roberson
Walter Roberson on 30 Oct 2018
Put
while true
At the top, and put
end
At the bottom.
Next question is how you are going to get out of the loop instead of having to enter values for the rest of the life of the computer.

Categories

Find more on Dialog Boxes in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!