Example 1
import java.util.Scanner;/** * Created by liwenj on 2017/7/17. */public class test7 {public static void main(String[] args) { Scanner input=new Scanner(System.in);int money=input.nextInt();if(money>500){ System.out.println("我要买一个凯迪拉克"); }else if(money>100){ System.out.println("我要买一个帕萨特"); }else if(money>50){ System.out.println("我要买一个伊兰特"); }else if(money>10){ System.out.println("我要买一个奥拓"); }else{ System.out.println("我要买一个拖拉机"); } } }
Example 2
import java.util.Scanner;/** * Created by liwenj on 2017/7/17. */public class test8 {public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("请输入是否是会员"); String huiyuan = input.next();boolean f = huiyuan.equals("yes"); System.out.println("请输入消费金额");double money = input.nextDouble();if (f) {if (money >= 200) {double dazhe = money * 0.75; System.out.println("你消费:" + dazhe); } else {double dazhe = money * 0.8; System.out.println("你消费:" + dazhe); } } else if (money >= 100) {double dazhe = money * 0.9; System.out.println("你消费:" + dazhe); }else{ System.out.println("你消费:"+money); } } }
Excessively long multi-branch structures are often regarded as software The bad structure in it, because it violates the OCP principle (open and closed principle), whenever a new conditional judgment processing needs to be added, an if-else branch must be added.
In many cases, using a function table structure is an effective way to avoid overly long branch structures. The following is a solution algorithm for the "Wolf, Sheep and Vegetable Crossing the River" problem using a function table structure instead of an overly long branch structure. Example of multi-branch structure. The farmer can take a total of 8 actions, and each action corresponds to a state transition processing process. If an if-else multi-branch structure is used, the code for processing state transitions will be very long. In order to avoid excessively long branch jump codes, the algorithm uses a function table structure. First declare the definition of the function table entry:
print? typedef bool (*ProcessFuncPtr)(const ItemState& current, ItemState& next); struct ActionProcess{ Action act; ProcessNextFuncPtr processFunc; }
The above is the detailed content of Introduction to if processing multi-branch structure examples and the shortcomings of too long if statements. For more information, please follow other related articles on the PHP Chinese website!