Illegal use of reserved keyword "else".

조회 수: 79 (최근 30일)
Mathidiot Superfacial
Mathidiot Superfacial 2016년 1월 6일
댓글: John D'Errico 2016년 1월 6일
  • d=input('waht');
  • if d==1
  • fprinf('d=%f',d);
  • else if d==2
  • fprinf('d=%f',d);
  • end
  • else if d==3
  • fprinf('d=%f',d);
  • end
  • else if d==4
  • fprinf('d=%f',d);
  • end
  • end
Why codes above show illegal use of keyword "else"?
  댓글 수: 1
Stephen23
Stephen23 2016년 1월 6일
편집: Stephen23 2016년 1월 6일
Why did you just change your question from code text formatting to a totally useless bullet points? The original (code) formatting showed the poor indentation, as the monospace code formatting shows the leading space characters. The correct way to format code text is to:
  1. paste the code
  2. select it
  3. click the {} Code button.
Using bullet-points makes it harder for us to help you, because we cannot simply copy your code to run it. It also hides any (poor) code indentation.

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

채택된 답변

Stephen23
Stephen23 2016년 1월 6일
편집: Stephen23 2016년 1월 6일
This code is a good example of why badly formatted code causes so many problems. Why do beginners avoid using the inbuilt editor's default indenting? When the code is indented properly, then some of the problems become clearer:
d=input('waht');
if d==1
fprinf('d=%f',d);
else
if d==2
fprinf('d=%f',d);
end
else
if d==3
fprinf('d=%f',d);
end
else
if d==4
fprinf('d=%f',d);
end
end
Do you see that the second and third else statements do not correspond to any if statement? This is also clearly highlighted in the MATLAB editor, with orange underline indicating a syntax error. Click on the line to get info about the error. Note that MATLAB supports elseif, but else if has no special meaning.
It is likely that the author really intended something more like this (using switch would be even neater):
d=input('waht');
if d==1
fprinf('d=%f',d);
elseif d==2
fprinf('d=%f',d);
elseif d==3
fprinf('d=%f',d);
elseif d==4
fprinf('d=%f',d);
end
Although given that every case is identical, the whole code could be replaced with this anyway:
d=input('waht');
fprinf('d=%f',d);
The other problems will be discovered shortly, such as fprintf being spelled incorrectly.
  댓글 수: 1
John D'Errico
John D'Errico 2016년 1월 6일
Another option is to use a switch construct.
d=input('what');
switch d
case 1
fprinf('d=%f',d);
case 2
fprinf('d=%f',d);
case 3
fprinf('d=%f',d);
case 4
fprinf('d=%f',d);
end
And, sorry, but I had to spell "what" properly.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by