收藏列表
标题 | 标签 | 来源 | |
规则拆分 | 压栈思想计算Java运算表达式 | ||
import java.util.HashMap; import java.util.Map; import java.util.Stack; import java.util.StringTokenizer; import java.util.Vector; import java.util.regex.Pattern; public class Test { public static void main(String args[]) { String computeExpr = "1 + 5 * 6 + 3 * (2 + 3*2+2-1+3*3) + 10/5 - 6*1"; Test test = new Test(); double result1 = test.computeWithVector(computeExpr); double result2 = test.computeWithStack(computeExpr); System.out.println(result1 + "=======" + result2); } /** * 利用java.util.Vector计算四则运算字符串表达式的值,如果抛出异常,则说明表达式有误,这里就没有控制 * @param computeExpr 四则运算字符串表达式 * @return 计算结果 */ public double computeWithVector(String computeExpr) { StringTokenizer tokenizer = new StringTokenizer(computeExpr, "+-*/()", true); Vector<Double> nums = new Vector<Double>(); Vector<Operator> operators = new Vector<Operator>(); Map<String, Operator> computeOper = this.getComputeOper(); Operator curOper; String currentEle; while (tokenizer.hasMoreTokens()) { currentEle = tokenizer.nextToken().trim(); if (!"".equals(currentEle)) {//只处理非空字符 if (this.isNum(currentEle)) { // 数字 nums.add(Double.valueOf(currentEle)); } else { // 非数字,即括号或者操作符 curOper = computeOper.get(currentEle); if (curOper != null) { // 是运算符 // 运算列表不为空且之前的运算符优先级较高则先计算之前的优先级 while (!operators.isEmpty() && operators.lastElement().priority() >= curOper .priority()) { compute(nums, operators); } // 把当前运算符放在运算符队列的末端 operators.add(curOper); } else { // 括号 if ("(".equals(currentEle)) { // 左括号时直接放入操作列表中 operators.add(Operator.BRACKETS); } else {// 当是右括号的时候就把括号里面的内容执行了。 // 循环执行括号里面的内容直到遇到左括号为止。试想这种情况(2+5*2) while (!operators.lastElement().equals(Operator.BRACKETS)) { compute(nums, operators); } //移除左括号 operators.remove(operators.size()-1); } } } } } // 经过上面代码的遍历后最后的应该是nums里面剩两个数或三个数,operators里面剩一个或两个运算操作符 while (!operators.isEmpty()) { compute(nums, operators); } return nums.firstElement(); } /** * 利用java.util.Stack计算四则运算字符串表达式的值,如果抛出异常,则说明表达式有误,这里就没有控制 * java.util.Stack其实也是继承自java.util.Vector的。 * @param computeExpr 四则运算字符串表达式 * @return 计算结果 */ public double computeWithStack(String computeExpr) { //把表达式用运算符、括号分割成一段一段的,并且分割后的结果包含分隔符 StringTokenizer tokenizer = new StringTokenizer(computeExpr, "+-*/()", true); Stack<Double> numStack = new Stack<Double>(); //用来存放数字的栈 Stack<Operator> operStack = new Stack<Operator>(); //存放操作符的栈 Map<String, Operator> computeOper = this.getComputeOper(); //获取运算操作符 String currentEle; //当前元素 while (tokenizer.hasMoreTokens()) { currentEle = tokenizer.nextToken().trim(); //去掉前后的空格 if (!"".equals(currentEle)) { //只处理非空字符 if (this.isNum(currentEle)) { //为数字时则加入到数字栈中 numStack.push(Double.valueOf(currentEle)); } else { //操作符 Operator currentOper = computeOper.get(currentEle);//获取当前运算操作符 if (currentOper != null) { //不为空时则为运算操作符 while (!operStack.empty() && operStack.peek().priority() >= currentOper.priority()) { compute(numStack, operStack); } //计算完后把当前操作符加入到操作栈中 operStack.push(currentOper); } else {//括号 if ("(".equals(currentEle)) { //左括号时加入括号操作符到栈顶 operStack.push(Operator.BRACKETS); } else { //右括号时, 把左括号跟右括号之间剩余的运算符都执行了。 while (!operStack.peek().equals(Operator.BRACKETS)) { compute(numStack, operStack); } operStack.pop();//移除栈顶的左括号 } } } } } // 经过上面代码的遍历后最后的应该是nums里面剩两个数或三个数,operators里面剩一个或两个运算操作符 while (!operStack.empty()) { compute(numStack, operStack); } return numStack.pop(); } /** * 判断一个字符串是否是数字类型 * @param str * @return */ private boolean isNum(String str) { String numRegex = "^\\d+(\\.\\d+)?$"; //数字的正则表达式 return Pattern.matches(numRegex, str); } /** * 获取运算操作符 * @return */ private Map<String, Operator> getComputeOper() { return new HashMap<String, Operator>() { // 运算符 private static final long serialVersionUID = 7706718608122369958L; { put("+", Operator.PLUS); put("-", Operator.MINUS); put("*", Operator.MULTIPLY); put("/", Operator.DIVIDE); } }; } /** * 取nums的最后两个数字,operators的最后一个运算符进行运算,然后把运算结果再放到nums列表的末端 * @param nums * @param operators */ private void compute(Vector<Double> nums, Vector<Operator> operators) { Double num2 = nums.remove(nums.size() - 1); // 第二个数字,当前队列的最后一个数字 Double num1 = nums.remove(nums.size() - 1); // 第一个数字,当前队列的最后一个数字 Double computeResult = operators.remove(operators.size() - 1).compute( num1, num2); // 取最后一个运算符进行计算 nums.add(computeResult); // 把计算结果重新放到队列的末端 } /** * 取numStack的最顶上两个数字,operStack的最顶上一个运算符进行运算,然后把运算结果再放到numStack的最顶端 * @param numStack 数字栈 * @param operStack 操作栈 */ private void compute(Stack<Double> numStack, Stack<Operator> operStack) { Double num2 = numStack.pop(); // 弹出数字栈最顶上的数字作为运算的第二个数字 Double num1 = numStack.pop(); // 弹出数字栈最顶上的数字作为运算的第一个数字 Double computeResult = operStack.pop().compute( num1, num2); // 弹出操作栈最顶上的运算符进行计算 numStack.push(computeResult); // 把计算结果重新放到队列的末端 } /** * 运算符 */ private enum Operator { /** * 加 */ PLUS { @Override public int priority() { return 1; } @Override public double compute(double num1, double num2) { return num1 + num2; } }, /** * 减 */ MINUS { @Override public int priority() { return 1; } @Override public double compute(double num1, double num2) { return num1 - num2; } }, /** * 乘 */ MULTIPLY { @Override public int priority() { return 2; } @Override public double compute(double num1, double num2) { return num1 * num2; } }, /** * 除 */ DIVIDE { @Override public int priority() { return 2; } @Override public double compute(double num1, double num2) { return num1 / num2; } }, /** * 括号 */ BRACKETS { @Override public int priority() { return 0; } @Override public double compute(double num1, double num2) { return 0; } }; /** * 对应的优先级 * @return */ public abstract int priority(); /** * 计算两个数对应的运算结果 * @param num1 第一个运算数 * @param num2 第二个运算数 * @return */ public abstract double compute(double num1, double num2); } } |
|||
freemaker讲解 | FreeMarker指令学习 | ||
if, else, elseif 语法: <#if condition> ... <#elseif condition2> ... <#elseif condition3> ... ... <#else> ... </#if> 备注:condition、condition2···必须为boolean 类型,<#elseif ··>、<#else>可有0或多个。 实例: <#if x == 1> x is 1 <#elseif x == 2> x is 2 <#elseif x == 3> x is 3 <#elseif x > 4> x is 4 <#else> x is not 1 nor 2 nor 3 nor 4 </#if> 备注:< 或 > 号 必须转义,否则出错。。转义请参考其他文档。 switch, case, default, break 语法 <#switch value> <#case refValue1> ... <#break> <#case refValue2> ... <#break> ... <#case refValueN> ... <#break> <#default> ... </#switch> 备注:该指令官方不推荐使用了,可以用if, else, elseif 指令代替。 list, break 语法 <#list sequence as item> ... </#list> 备注: sequence 为一个sequence 或者 collection 类型。item 为 循环的变量。该指令中包含有两个特殊的循环变量, item_index:该值为当前循环的值。 item_has_next:该值为一个boolean类型,表明该循环是否含有下一个(是否为循环到了最后一个) 实例: <#assign seq = ["winter", "spring", "summer", "autumn"]> <#list seq as x> ${x_index + 1}. ${x}<#if x_has_next>,</#if> </#list> 输出: 1. winter, 2. spring, 3. summer, 4. autumn 实例: <#assign x=3> <#list 1..x as i> ${i} </#list> 备注:当x 为一个数值序列时,可以使用该list 列出两个数值之间的值。(适合于表格的序号填写) 实例: <#list seq as x> ${x} <#if x = "spring"><#break></#if> </#list> 备注:可以用<#if···><#break> 来终止该循环。 include 语法 <#include path> 或者 <#include path options> 备注: path: 为包含一个文件的路径或者是一个输出为String 类型的表达式。 options: 一个或多个的参数: encoding=encoding, parse=parse encoding: 包含文件解析的编码,如GBK、utf-8等 parse: 为一个boolean 类型值,true为用ftl解析,false为当作text文件解析 (also accepts a few string values for backward compatibility) 实例: /common/copyright.ftl内容: Copyright 2001-2002 ${me}<br> All rights reserved. 主体内容: <#assign me = "Juila Smith"> <h1>Some test</h1> <p>Yeah. <hr> <#include "/common/copyright.ftl"> 输出 <h1>Some test</h1> <p>Yeah. <hr> Copyright 2001-2002 Juila Smith All rights reserved. 备注:path 可以包含*任意取值,例如:*/copyright.ftl、commons/*/copyright.ftl等,*表示任意路径下的。 该指令具有国际化,如<#include "footer.ftl">, 这个指令的搜索文件的顺序为footer_en_US.ftl,footer_en.ftl,footer.ftl (本地为英国)。 import 语法: <#import path as hash> 备注: path:模板的路径名. hash: 在该文件中使用该模板指令的名称。 实例: <#import "/libs/mylib.ftl" as my> 文件中的使用: <@my.copyright date="1999-2002"/> noparse 语法: <#noparse> ... </#noparse> 备注:该指令包含的文件将不被解析成ftl,而是直接输出。 实例: Example: -------- <#noparse> <#list animals as being> <tr><td>${being.name}<td>${being.price} Euros </#list> </#noparse> 输出: Example: -------- <#list animals as being> <tr><td>${being.name}<td>${being.price} Euros </#list> compress 语法: <#compress> ... </#compress> 备注:该指令将会把数据模型中的空格或者html格式去掉。 实例: <#assign x = " moo \n\n "> (<#compress> 1 2 3 4 5 ${moo} test only I said, test only </#compress>) 输出: (1 2 3 4 5 moo test only I said, test only) escape, noescape 语法: <#escape identifier as expression> ... <#noescape>...</#noescape> ... </#escape> 备注:该指令对${```}该指令进行了格式化的输出。 备注: <#escape x as x?html> Customer Name: ${customerName} Items to ship: <#escape x as itemCodeToNameMap[x]> ${itemCode1} ${itemCode2} ${itemCode3} ${itemCode4} </#escape> </#escape> 相当于: Customer Name: ${customerName?html} Items to ship: ${itemCodeToNameMap[itemCode1]?html} ${itemCodeToNameMap[itemCode2]?html} ${itemCodeToNameMap[itemCode3]?html} ${itemCodeToNameMap[itemCode4]?html} assign 语法: <#assign name=value> or <#assign name1=value1 name2=value2 ... nameN=valueN> or <#assign same as above... in namespacehash> or <#assign name> capture this </#assign> or <#assign name in namespacehash> capture this </#assign> 备注:该指令可以创建或者替换变量为页面使用,该变量为最高的层才能被创建或替换,如foo,当foo.bar时将不能被创建或者替换。 name:变量的名称。value:变量的值。namespacehash:import指令中的引用名。 实例: <#assign seasons = ["winter", "spring", "summer", "autumn"]> <#assign seasons = ["winter", "spring", "summer", "autumn"] test = test + 1 > 实例: <#import "/mylib.ftl" as my> <#assign bgColor="red" in my> 实例: <#macro myMacro>foo</#macro> <#assign x> <#list 1..3 as n> ${n} <@myMacro /> </#list> </#assign> Number of words: ${x?word_list?size} ${x} 输出: Number of words: 6 1 foo 2 foo 3 foo global 语法: <#global name=value> or <#global name1=value1 name2=value2 ... nameN=valueN> or <#global name> capture this </#global> 备注:该指令相似于assign 指令,只是该指令创建的变量可以被所有命名空间使用。 实例: <#global x = 1> <#assign x = 2> ${x} ${.global.x} </#assign> 输出: 2 1 备注:如果在当前命名空间中,有同名的变量存在,则global 变量将没隐藏,如需访问则:${.global.x} local 语法: <#local name=value> or <#local name1=value1 name2=value2 ... nameN=valueN> or <#local name> capture this </#local> 备注:该指令类似 assign 指令,但它创建或者替换了本例变量,它只能在macro定义或者function 定义中有效。 setting 语法: <#setting name=value> 备注:该指令的设置将影响到该指令设置的地方以下的内容有效。 它提供的设值有: local:该值为本地的语言,将影响数值、时间等的格式。取值例如:en, en_US, en_US_MAC number_format:用于将数值转换成String,当没有明确的格式被指定时。 boolean_format:用于将boolean转换成String date_format,time_format,datetime_format:用于将时间转换成String time_zone:用于设置时区,如"GMT", "GMT+2", "GMT-1:30", "CET", "PST", "America/Los_Angeles" url_escaping_charset: classic_compatible: 实例: ${1.2} <#setting locale="en_US"> ${1.2} 输出: 1,2 1.2 User-defined directive (<@...>) 语法: <@user_def_dir_exp param1=val1 param2=val2 ... paramN=valN/> (Note the XML-style / before the >) or if you need loop variables <@user_def_dir_exp param1=val1 param2=val2 ... paramN=valN ; lv1, lv2, ..., lvN/> Or the same as the above two but with end-tag <@user_def_dir_exp ...> ... </@user_def_dir_exp> or <@user_def_dir_exp ...> ... </@> Or all above but with positional parameter passing <@ val1, val2, ..., valN/> ...etc. 备注:该指令为调用用户自定义的指令,比如macro 实例: <@list items=["mouse", "elephant", "python"] title="Animals"/> ... <#macro list title items> <p>${title?cap_first}: <ul> <#list items as x> <li>${x?cap_first} </#list> </ul> </#macro> 输出: <p>Animals: <ul> <li>Mouse <li>Elephant <li>Python </ul> ... 实例: <@myRepeatMacro count=4 ; x, last> ${x}. Something... <#if last> This was the last!</#if> </@myRepeatMacro> macro, nested, return 语法: <#macro name param1 param2 ... paramN> ... <#nested loopvar1, loopvar2, ..., loopvarN> ... <#return> ... </#macro> 备注:该指令保存着模板的部分定义,可以用用户指令来调用该指令使用。该指令可以定义在任何地方,不管设定的地方之前或者之后都能使用。也可以指定默认参数的默认值。 实例: <#macro test foo bar="Bar" baaz=-1> Test text, and the params: ${foo}, ${bar}, ${baaz} </#macro> <@test foo="a" bar="b" baaz=5*5-2/> <@test foo="a" bar="b"/> <@test foo="a" baaz=5*5-2/> <@test foo="a"/> 输出: Test text, and the params: a, b, 23 Test text, and the params: a, b, -1 Test text, and the params: a, Bar, 23 Test text, and the params: a, Bar, -1 实例: <#macro img src extra...> <img src="/context${src?html}" <#list extra?keys as attr> ${attr}="${extra[attr]?html}" </#list> > </#macro> <@img src="/images/test.png" width=100 height=50 alt="Test"/> 输出: <img src="/context/images/test.png" alt="Test" height="50" width="100" > 实例: <#macro do_thrice> <#nested 1> <#nested 2> <#nested 3> </#macro> <@do_thrice ; x> ${x} Anything. </@do_thrice> 输出: 1 Anything. 2 Anything. 3 Anything. 实例: <#macro test> Test text <#return> Will not be printed. </#macro> <@test/> 输出: Test text function, return 语法: <#function name param1 param2 ... paramN> ... <#return returnValue> ... </#function> 备注:该指令创建了一个方法变量,该指令和macro指令类似,只是return 中必须有返回值。 实例: <#function avg x y> <#return (x + y) / 2> </#function> ${avg(10, 20)} 输出: 15 实例: <#function avg nums...> <#local sum = 0> <#list nums as num> <#local sum = sum + num> </#list> <#if nums?size != 0> <#return sum / nums?size> </#if> </#function> ${avg(10, 20)} ${avg(10, 20, 30, 40)} ${avg()!"N/A"} 输出: 15 25 N/A flush 语法: <#flush> 备注:强制输出。虽然FreeMarker会自动的flush 但有些时候要强制flash 的时候可以使用该指令。 stop 语法: <#stop> or <#stop reason> 备注:当FreeMarker要强制终止的时候,可以使用该指令,reason 为自定义终止的原因。 ftl 语法: <#ftl param1=value1 param2=value2 ... paramN=valueN> 备注:该指令是提供一些参数如果该文件是ftl文件,如果该文件存在则该设置在文件的最开始的地方。 设置的参数有: encoding:模板的编码,取值为:utf-8、GBK等 strip_whitespace:是否去掉空格。取值为true、false strip_text:是否去掉最高层的文本,取值为true、false strict_syntax:是否为严格的语法,取值为true、false ns_prefixes: attributes: t, lt, rt 语法 <#t> -在该行中忽略所有的空格 <#lt> -在该行中忽略左边的所有空格 <#rt> -在该行中忽略右边的所有空格 <#nt> -不去掉该行的空格 实例: -- 1 <#t> 2<#t> 3<#lt> 4 5<#rt> 6 -- 输出: -- 1 23 4 5 6 -- attempt, recover 语法: <#attempt> attempt block <#recover> recover block </#attempt> 备注:该指令是一个错误的捕获,和java 中的 try{}catch 相似。<#recover>是修复指令,代替出错的输出文本。 实例: Primary content <#attempt> Optional content: ${thisMayFails} <#recover> Ops! The optional content is not available. </#attempt> Primary content continued 输出: 如果thisMayFails 变量不存在 Primary content Ops! The optional content is not available. Primary content continued 如果thisMayFails 变量存在 Primary content Optional content: 123 Primary content continued visit, recurse, fallback 语法: <#visit node using namespace> or <#visit node> <#recurse node using namespace> or <#recurse node> or <#recurse using namespace> or <#recurse> <#fallback> 备注:visit 和recurse 指令是用来递归处理树节点的。在实际中,很多情况下是用来处理xml。 实例: <#-- Assume that nodeWithNameX?node_name is "x" --> <#visit nodeWithNameX> Done. <#macro x> Now I'm handling a node that has the name "x". Just to show how to access this node: this node has ${.node?children?size} children. </#macro> 输出: Now I'm handling a node that has the name "x". Just to show how to access this node: this node has 3 children. Done. 实例: 主体 <#import "n1.ftl" as n1> <#import "n2.ftl" as n2> <#-- This will call n2.x (because there is no n1.x): --> <#visit nodeWithNameX using [n1, n2]> <#-- This will call the x of the current namespace: --> <#visit nodeWithNameX> <#macro x> Simply x </#macro> n1.ftl <#macro y> n1.y </#macro> n2.ftl: <#macro x> n2.x <#-- This will call n1.y, becuase it inherits the "using [n1, n2]" from the pending visit call: --> <#visit nodeWithNameY> <#-- This will call n2.y: --> <#visit nodeWithNameY using .namespace> </#macro> <#macro y> n2.y </#macro> 输出: n2.x n1.y n2.y Simply x |
|||
定时任务 | java 定时 Java:Web应用下实现后台定时任务 | ||
package lbs.client.systemservice; import java.util.Timer; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.apache.commons.lang.time.DateUtils; public class TaskManager implements ServletContextListener { //每天的毫秒数 public static final long PERIOD_DAY = DateUtils.MILLIS_IN_DAY; //一周的毫秒数 public static final long PERIOD_WEEK = PERIOD_DAY * 7; //无延迟 public static final long NO_DELAY = 0; //定时器 private Timer timer; /** * 在Web应用结束时停止任务 */ public void contextDestroyed(ServletContextEvent sce) { timer.cancel();//定时器销毁 } /** * 在Web应用启动时初始化任务 */ public void contextInitialized(ServletContextEvent sce) { //定义定时器 timer = new Timer(true); //timer.schedule(new LocationTask(), NO_DELAY, PERIOD_WEEK * 4); timer.schedule(new LocationTask(), NO_DELAY, 30000); } } |
|||
sendmail结合freemaker | OFBiz的邮件发送实现,仅用javax.mail.*包非spring,适合所有情况 | ||
Public static String getBody(Map<String, String> map, String tmpName) { StringWriter result = new StringWriter();//输出流 String path = UtilProperties.getConfigureMessage("email.template.path");//freemarker模板地址 if (tmpName == null) { path +="test";//默认模板 } else { path += tmpName; } try { Template template = FreeMarkerWorker.getTemplate(path);//取模板 template.process(map, result);//将所给的map中K,Value值与模板中的值相匹配,将结果放入输出流 //注意,map中的键值对一定要和模板中的值相匹配 } catch (TemplateException e1) { Debug.logError(e1.getMessage().toString(), module); } catch (IOException e1) { Debug.logError(e1.getMessage().toString(), module); } String body = result.toString(); return body; } |