clc;clear
C1 = input('Please enter a code to break: ' , 's');
if length(C1) ~= 6
disp('Decoy message: Not a six-digit number.');
else
A = mod(sum(C1 - '0'),2);
if A == 1
disp('Decoy message: Sum is odd.')
else
C2 = (C1(1) - '0') * (C1(2) - '0') - (C1(3) - '0');
failed = false;
switch C2
case 1
Day = 'Rescue on Monday';
case 2
Day = 'Rescue on Tuesday';
case 3
Day = 'Rescue on Wednesday';
case 4
Day = 'Rescue on Thursday';
case 5
Day = 'Rescue on Friday';
case 6
Day = 'Rescue on Saturday';
case 7
Day = 'Rescue on Sunday';
otherwise
disp('Decoy message: Invalid rescue day.');
failed = true;
end
F1 = str2double(C1(4));
F2 = str2double(C1(5));
F3 = str2double(C1(6));
if mod(F1,3) == 0
B = F2 - F3;
else
B = F3 - F2;
end
if ~failed
switch(B)
case 1
Position = ' at the bridge.';
case 2
Position = ' at the library.';
case 3
Position = ' at the river crossing.';
case 4
Position = ' at the airport.';
case 5
Position = ' at the bus terminal.';
case 6
Position = ' at the hospital.';
case 7
Position = ' at St. Petes Church.';
otherwise
disp('Decoy message: Invalid rendezvous point.');
end
disp([Day , Position])
end
end
end
If I enter 918990, I do get what I want, it will show Decoy message: Invalid rendezvous point. But there will appear an error message, how I can debug this?

 채택된 답변

Dana
Dana 2020년 9월 25일
편집: Dana 2020년 9월 25일

0 개 추천

The error is because if you end up in the "otherwise" case of your switch(B), the variable Position doesn't ever get defined, so when you try to do disp([Day , Position]) it causes an error. To avoid this, you can just put a return statement:
.
.
.
otherwise
disp('Decoy message: Invalid rendezvous point.');
return
end
disp([Day , Position])
end
end
end

댓글 수: 6

Minhao Wang
Minhao Wang 2020년 9월 25일
thank you so much!
Minhao Wang
Minhao Wang 2020년 9월 29일
sry, I have another question, I just realize this homework does not allowed us to use 'return' statement. Any other suggestion?
Dana
Dana 2020년 9월 29일
You could set up a flag that tracks whether you ended up in the "otherwise" case (essentially what you did with your failed variable), and use that to decide whether the disp([Day , Position]) step gets executed.
Minhao Wang
Minhao Wang 2020년 9월 29일
Can you please show me how is it done? I am a bit lost to set up a flag in this situation....
Minhao Wang
Minhao Wang 2020년 9월 29일
oh, okay i got it ! thank you !
Dana
Dana 2020년 9월 29일
You already did it once with your failed variable: you set it equal to false initially, and then if you ended up in your "otherwise" case you switched it to true, and then you only proceeded to the switch(B) statement if failed=false. It's exactly the same logic in this case.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

태그

질문:

2020년 9월 25일

댓글:

2020년 9월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by