1. 使用IF 语句实现分支,IF语句实现分支有3种类型
1.1 若发生了某事该怎样处理.
DATA: X TYPE N VALUE 6.
IF X = 5. WRITE:/ 'The value of x is 5'."輸出:The value of x is 5ENDIF.
1.2 若發生了某事則怎麼辦,否則該如何處理。
DATA: X TYPE N VALUE 6.IF X = 5. WRITE:/ 'The value of x is 5'.ELSE. WRITE:/ 'The value of x is 6'."輸出:The value of x is 6ENDIF.
1.3 嵌套使用 IF...ELSE进行多个条件判断。
IF <condition1>. <statement block>. ELSEIF <condition2>. <statement block>. ELSE. <statement block> ENDIF.
DATA: X TYPE N VALUE 7.IF X = 5. WRITE:/ 'The value of x is 5'.ELSEIF X = 6. WRITE:/ 'The value of x is 6'.ELSE. WRITE:/ 'The value of x is 7'."輸出:The value of x is 7ENDIF.
2.例用CASE...WHEN...ENDCASE语句实现分支。
当程序面临多个交叉条件时,就可以使用CASE 语句进行分去。
CASE <f>.
WHEN <f1>. <statement block>. WHEN <f2>. <statement block>. WHEN ... WHEN OTHERS. <statement block>. ENDCASE. DATA:X TYPE N VALUE 8.CASE X. WHEN 1. WRITE:/ 'The NO.ONE'. WHEN 2. WRITE:/ 'The NO.TWO'. WHEN OTHERS. WRITE:/ 'Others NO.'."输出:Others NO.ENDCASE.3. 使用LOOP...ENDLOOP语句实现循环控制
LOOP语句通常用于实现内表数据的循环读取及操作.
LOOP AT ITAB.
WRITE:ITAB.ENDLOOP.4. 使用DO语句实现内部循环次数控制
4.1 DO语句可以指定循环资数.
DO 5 TIMES.
WRITE:/ 'THE index is',SY-INDEX.ENDDO.
4.2 DO语句内部还可以实现多层嵌套,为了保证程序可读性,建议嵌套最多不可超过6层。
DO. [<n> TIMES] [VARYING <f> FROM <f1> NEXT <f2>]. <statement block> ENDDO. n:可以是数字或者变量,如果n是0或者负数,系统不执行该循环. TIMES:循环次数。 VARYING:选项在每次循环中给变量<f>重新赋值。 使用DO语句时要避免死循环,如果不使用TIMES选项,则在语句块中至少包含一个EXIT、STOP、REJECT语句,以使系统能退出循环。
DO 5 TIMES.
WRITE:/ 'The index is',SY-INDEX.DO 2 TIMES.WRITE:/ 'The Next index is',SY-INDEX.ENDDO.ENDDO.
5. 使用ONCHANGE 实现循环内部数据管控
当循环中的数据值发生变动时,可以用表达式ONCHANGE来触发数值变动事件。
DO 5 TIMES.
ON CHANGE OF SY-INDEX.WRITE:/ 'The index is',SY-INDEX.ENDON.ENDDO.DATA WHILE_INDEX TYPE N VALUE 0.WHILE WHILE_INDEX < 5. WHILE_INDEX = WHILE_INDEX + 1. DO 2 TIMES. ON CHANGE OF WHILE_INDEX. WRITE:/ 'The while_index has change value is',WHILE_INDEX. ENDON. WRITE:/ 'SY-INDEX=',SY-INDEX. ENDDO.ENDWHILE.
6.循环的中止
6.1 CONTINUE语句用于结束当前循环进行下一步循环。
6.2 EXIT语句用于结束当前整个循环。
DO 100 TIMES.
IF SY-INDEX = 10 AND SY-INDEX <= 20. CONTINUE.ELSEIF SY-INDEX = 50. EXIT.ELSE. WRITE: SY-INDEX.ENDIF.ENDDO.
7. 使用WHILE 条件循环
WHILE <condition> [VARY <f> FROM <f1> NEXT <f2>].
<statement block> ENDWHILE.DATA WHILE_INDEX TYPE N VALUE 0.
WHILE WHILE_INDEX < 5. WHILE_INDEX = WHILE_INDEX + 1. IF WHILE_INDEX = 3. CONTINUE. ENDIF. WRITE:/ 'while_index',WHILE_INDEX.ENDWHILE.
有条件终止循环(CHECK):
DATA while_index TYPE N VALUE 0.
WHILE while_index < 5. while_index = while_index + 1. CHECK while_index BETWEEN 2 AND 5. WRITE:/ 'The while_index is',while_index.ENDWHILE.
完全终止循环(EXIT):
DATA WHILE_INDEX TYPE N VALUE 0.
WHILE WHILE_INDEX < 5. WHILE_INDEX = WHILE_INDEX + 1. IF WHILE_INDEX = 3. EXIT. ENDIF. WRITE:/ 'The while_index is',while_index.ENDWHILE.