`
xuchunming
  • 浏览: 30226 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

http://sourcemaking.com/design_patterns/interpreter/java/2

阅读更多
public class InterpreterDemo {
   public static boolean precedence( char a, char b ) {
      String high = "*/", low = "+-";
      if (a == '(') return false;     // if (a == '(' && b == ')') return false;
      if (a == ')'  &&  b == '(') { System.out.println( ")-(" ); return false; }
      if (b == '(') return false;
      if (b == ')') return true;
      if (high.indexOf( a ) > -1  &&  low.indexOf( b )  > -1) return true;
      if (high.indexOf( a ) > -1  &&  high.indexOf( b ) > -1) return true;
      if (low.indexOf( a ) > -1   &&  low.indexOf( b )  > -1) return true;
      return false;
   }
   public static String convertToPostfix( String in ) {
      StkChar      opstk  = new StkChar();
      StringBuffer out    = new StringBuffer();
      String       opers  = "+-*/()";
      char         topsym = '+';
      boolean      empty;

      for (int i = 0; i < in.length(); i++)
         if (opers.indexOf( in.charAt(i) ) == -1)
            out.append( in.charAt(i) );
         else {
            while ( ! (empty = opstk.isEmpty())
                    &&  precedence( topsym = opstk.pop(), in.charAt(i) ))
               out.append( topsym );
            if ( ! empty)                     opstk.push( topsym );
            if (empty || in.charAt(i) != ')') opstk.push( in.charAt(i) );
            else                              topsym = opstk.pop();
         }
      while ( ! opstk.isEmpty()) out.append( opstk.pop() );
      return out.toString();
   }
   public static int evaluate( String in ) {
      StkInt stack = new StkInt();
      String opers = "+-*/";
      for (int a, b, i=0; i < in.length(); i++)
         if (opers.indexOf( in.charAt(i) ) == -1)
            stack.push( in.charAt(i)-48 );
         else {
            b = stack.pop();  a = stack.pop();
            if      (in.charAt(i) == '+') a = a + b;
            else if (in.charAt(i) == '-') a = a - b;
            else if (in.charAt(i) == '*') a = a * b;
            else if (in.charAt(i) == '/') a = a / b;
            stack.push( a );
         }
      return stack.pop();
   }
   public static void main( String[] args ) {
      System.out.print( args[0] );
      String postfix = convertToPostfix( args[0] );
      System.out.print( " -- " + postfix );
      System.out.println( " -- " + evaluate( postfix ) );
} 

class StkChar {
   private char[] arr = new char[9];
   private int    sp  = -1;
   void    push( char ch ) { if ( ! isFull()) arr[++sp] = ch; }
   char    pop()           { if (isEmpty()) return '\0';  return arr[sp--]; }
   boolean isFull()        { return sp == arr.length-1; }
   boolean isEmpty()       { return sp == -1; }
}

class StkInt {
   private int[] arr = new int[9];
   private int   sp  = -1;
   void    push( int ch ) { if ( ! isFull()) arr[++sp] = ch; }
   int     pop()          { if (isEmpty()) return 0;  return arr[sp--]; }
   boolean isFull()       { return sp == arr.length-1; }
   boolean isEmpty()      { return sp == -1; }
}}

2+3*4-5+6 -- 234*+5-6+ -- 15 (2+3)*4-5+6 -- 23+4*5-6+ -- 21 2+3*(4-5)+6 -- 2345-*+6+ -- 5 2+3*((4-5)+6) -- 2345-6+*+ -- 17 (3-(4*(5+6))/(7-8))*9/4 -- 3456+*78-/-9*4/ -- 105 
分享到:
评论

相关推荐

    Beginning Swift Programming.pdf

    Understand the key design patterns in iOS and Mac OS programming using protocols and delegates Learn how to use generics to create highly reusable code Learn the new access controls mechanism in Swift...

    UE(官方下载)

    Regular Expressions are essentially patterns (rather than specific strings) that are used with Find/Replace operations. This guide can dramatically improve your speed and efficiency for Find/Replace ...

    C++学习网站列表.txt

    2. Cygwin(http://sources.redhat.com/cygwin/) Cygwin提供了一个在Windows平台上运行类Unix环境的工具集,包括C++编译器和其他开发工具。 3. KAI C++(http://www.kai.com/) KAI C++是一个高性能的C++编译器...

    Ajax学习 网址备忘录.txt

    - **网址**:http://www.ajaxpatterns.org 和 http://www.softwareas.com/ajax-patterns - **简介**:该网站提供了一系列关于Ajax模式的资源,帮助开发者更好地设计和实现Ajax应用。 - **特色内容**: - 模式库 - ...

    三菱伺服电机选型软件Motorizer(中文):sw1dnn-mz-m_005f.zip.001

    Drive System Sizing Software Motorizer is software that enables you to select the most suitable servo motors for your machine just by ...machine configuration/specifications and the operation patterns....

    《Head First 设计模式》中文完整清晰pdf,配全目录书签,第二分卷

    这是本人过去收集网上的清晰扫描图片,和预览样章合并制成的pdf。由于当时是自已学习用,所以边看边制目录书签。现在放上来希望能攒点分。由于文件有127M大,所以...第七分卷:http://download.csdn.net/source/3000445

    三菱伺服电机选型软件Motorizer(中文):sw1dnn-mz-m_005f.zip.002

    Drive System Sizing Software Motorizer is software that enables you to select the most suitable servo motors for your machine just by ...machine configuration/specifications and the operation patterns....

    Microservices for Java EE Architects-DVT Press(2016).azw3

    Readers of the Java EE Architect’s Handbook, Second Edition are well acquainted with traditional application architectures. Since this book was published, microservices architecture has emerged. It ...

    人脸识别(face recognition)

    在人脸识别方面,OpenCV提供了EigenFace、FisherFace和LBPH(Local Binary Patterns Histograms)三种人脸识别算法。这些算法可以用于训练模型,以识别或验证人脸。例如,使用`cv2.CascadeClassifier`可以检测图像中...

    expect4j.jar 1.0

    Expect4j is an attempt to rewrite Expect in Java and provide bindings to the TclJava interpreter. The goal is to be able to port existing Tcl code bases that use Expect directly to Java without ...

    Web开发者欣喜若狂的40个UI设计工具和资源

    **网址**:http://ui-patterns.com/ #### PatternTap PatternTap是一个收集了广泛设计模板的平台,它将UI元素按类别整理,便于设计师快速找到灵感。每个项目都带有标签,可以在新窗口中单独查看,极大地提高了设计...

    <<设计模式>>GOF,C++实例源码

    This is my implementation of the Design Patterns from the book 'Design Patterns: Elements of Reusable Object-Oriented Software' Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides ISBN 0-201-...

    fatal error: boostdesc_bgm.i: No such file or directory补充文件

    3. `boostdesc_lbgm.i`: 可能是Local Binary Patterns三阶矩(LBP-TOP)的Boost实现,这是一种用于纹理分类和图像识别的方法。 4. `boostdesc_bgm_bi.i`: 这可能是指Boosting版本的GLOH(Generalized Local Order ...

    DesignPatterns.pdf_objects_designpatterns_

    标题中的"DesignPatterns.pdf_objects_designpatterns_"暗示了这可能是一个关于面向对象设计模式的PDF文档,而描述中的"Design patterns elements of reusable objects"进一步确认了这一点。设计模式的核心理念在于...

    Java教程补充材料

    14 Design Patterns 15 Text I/O Prior to JDK 1.5 (Reader and Writer Classes) 16 Assertions 17 Packaging and Deploying Java Projects 18 Java Web Start 19 Signed Java Applets 20 GridBagLayout ...

    GoF_Design_Patterns_Reference0100.pdf_designpatterns_ebookgof_De

    GOF Design Patterns ebook

    image_thumbnail_proxy:基于nginx+php的懒人缩略图代理

    #缩略图代理作者:sskaje( ) ##Supported URL patterns 来源: http://static.sskaje.me/path/to/image/abcd.jpg 缩略图: ...

    Node.js_Design_Patterns_Second_Edition_Code, node.js 设计模式第二版代码库,由Packt发布.zip

    Node.js_Design_Patterns_Second_Edition_Code, node.js 设计模式第二版代码库,由Packt发布 node.js 设计模式,第二版通过掌握最强大的组件和模式来创建模块化和可以伸缩的应用程序,从而轻松地从 node.js 中。...

    JAVA学习总结与JAVA书籍网站推荐.docx

    - `Concurrent Programming in Java: Design Principles and Patterns` 由Doug Lea撰写,是并发编程的经典之作,有第二版。 - `Refactoring` 由Martin Fowler等人合著,讨论了代码重构的重要性和方法。 - `Design...

    cloud-design-patterns微软中文翻译版本

    cloud-design-patterns微软中文翻译版本,AWS http://en.clouddesignpattern.org/index.php/Main_Page 微软 https://docs.microsoft.com/en-us/azure/architecture/patterns/

Global site tag (gtag.js) - Google Analytics