State model to solve the problem using the piecewise

problem:

There is a function:

y={ x      x<1
    | 2x-1   1<=x<10
    \ 3x-11  x>=10

Write a program, input x, output y

Code:

  There are two ways:

  The first: The easiest way to use the article ifelse piece judgment statement to achieve:

 1 import java.util.Scanner;
 2 
 3 public class Demo {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7         System.out.println("请输入一个数:");
 8         Scanner scanner=new Scanner(System.in);
 9         int x=scanner.nextInt();
10         if(x<1){
11             System.out.println(x);
12         }else if (1<=x&&x<10) {
13             System.out.println(2*x-1);
14         }else {
15             System.out.println(3*x-11);
16         }
17     }
18 
19 }

  This method is straightforward, but in practice, this method is not the highest efficiency, especially when faced with multiple choices judgment. And in the latter part of maintenance is not easy, often a change, always change, cause unnecessary trouble.

  It is proposed that the second method

  The second: to implement the problem with state mode (when not less than three selection condition, the recommended method)

  First of all, the first to write an abstract class status (status):

  

Guess you like

Origin www.cnblogs.com/wangjiong/p/11249270.html