Where should I add error checking to my program?

1 visualización (últimos 30 días)
Jennifer Coss
Jennifer Coss el 15 de Abr. de 2017
Comentada: Jennifer Coss el 16 de Abr. de 2017
I'm trying to create a program that simulates a dice roll. The instructions given are: Write a matlab funtion called hitTarget that will accept one scalar argument, the target sum of two random 6-sided dice rolls. The function generates and displays two random numbers between 1 and 6 (like dice rolls) until the sum of the two die equals the target argument. Keep track of how many rolls it takes.
Sample Run:
>> hitTarget(8)
5 2
6 3
2 2
4 3
3 5
Target met, it took 5 rolls.
My code so far:
function [] = hitTarget( target )
%if(target>=2 && target<=12 && isinteger(target))
count = 0;
dieTotal = 0;
while(dieTotal~=target)
count = count + 1;
dieOne = randi(6,1,1);
dieTwo = randi(6,1,1);
result = [dieOne dieTwo];
disp(result);
dieTotal = sum(result);
if(dieTotal==target)
disp(['Target met, it took ', num2str(count), ' rolls.']);
end
end
%end
end
I commented out the error checking statement I need because the program will not run at all if I leave it there. But I don't know where else to put it.
Thanks for any help!!!

Respuesta aceptada

Image Analyst
Image Analyst el 15 de Abr. de 2017
Editada: Image Analyst el 15 de Abr. de 2017
Replace the line
%if(target>=2 && target<=12 && isinteger(target))
with
if target<2 || target > 12
errorMessage = sprintf('A target of %d is not allowed.\n', target);
uiwait(errordlg(errorMessage));
return;
end
if ~isinteger(target)
errorMessage = sprintf('Fractional numbers are not allowed!');
uiwait(errordlg(errorMessage));
return;
end
% If it gets here, the target number is acceptable.

Más respuestas (0)

Community Treasure Hunt

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

Start Hunting!

Translated by