Rookie needing some help with if-else and switch case.
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Harpreet Saini
il 6 Ott 2016
Commentato: Harpreet Saini
il 6 Ott 2016
I am a first year engineering student with no knowledge or background on programming. I have only been doing it for two weeks. I need some help with one of the programming assignments. I am only copying partial question because it is too long. I know I am somehow making mistake at the second switch statement but I am not sure what am I doing wrong. Any help or hint would be really appreciated. Thank You
clc
code = input ('Please enter a code to break: ','s');
digits = code - '0';
if length (digits) ~= 6;
display ('Decoy Message: Not a six digit number')
else
if mod (sum (digits),2) == 1;
display ('Decoy Message: Sum is odd')
else
day = (digits(1)*digits(2))-digits(3);
switch day;
case 1
day = 'Monday';
case 2
day = 'Tuesday';
case 3
day = 'Wednesday';
case 4
day = 'Thursday';
case 5
day = 'Friday';
case 6
day = 'Saturday';
case 7
day = 'Sunday';
otherwise
display ('Decoy Message: Invalid rescue day')
end
if 1 < day || day > 7;
if mod (digits(4),3)==0;
point = digits(5)-digits(6);
else point = digits(6)-digits(5);
switch point;
case 1
point = 'bridge';
case 2
point = 'library';
case 3
point = 'river crossing';
case 4
point = 'airport';
case 5
point = 'bus terminal';
case 6
point = 'hospital';
case 7
point = 'St. Petes Church';
otherwise
display ('Decoy Message: Invalid rendezvous point')
end
end
end
end
end
2 Commenti
Risposta accettata
Guillaume
il 6 Ott 2016
I suggest you learn how to debug your program. Had you stepped through you program you would have quickly found the issue.
Just from reading the code, it is clear to me that there is an issue with
if 1 < day || day > 7;
if mod (digits(4),3)==0;
point = digits(5)-digits(6);
else point = digits(6)-digits(5);
switch point;
As written, the switch point only happens when you're in the else part of the if ... else. So, when mod(..) == 0 you calculate point but never use it. I would think you're missing an end after the else.
By the way, you don't normally write a semicolon after an if or a switch.
Note that a much neater replacement to your switch statements is to use simple indexing. For example for the day, I would use:
daynames = {'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'};
day = (digits(1)*digits(2))-digits(3)
assert(mod(day, 1) == 0 && day >= 1 && day <= 7, 'Decoy Message: Invalid rescue day'); %make sure day is integer between 1 and 7
day = daynames{day}; %note that you're using the same variable name for the numeric and string day. Not good practice
Più risposte (0)
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!