Java Scritp 常用代码大全(3)

合集下载

常用 it 代码

常用 it 代码

常用 it 代码常用 IT 代码引言:在当今信息技术高速发展的时代,IT代码成为了我们日常工作中不可或缺的一部分。

无论是开发软件、设计网站还是进行数据分析,IT代码都扮演着重要的角色。

本文将介绍一些常用的IT代码,并探讨它们在不同领域中的应用。

一、Python代码Python作为一种易于学习和使用的编程语言,被广泛应用于各个领域。

以下是一些常用的Python代码片段:1. 数据读取与处理:使用pandas库的read_csv函数读取CSV文件,并使用DataFrame进行数据处理和分析。

2. 网络爬虫:使用requests库发送HTTP请求,并使用BeautifulSoup解析网页内容。

3. 数据可视化:使用matplotlib库绘制各种类型的图表,如折线图、柱状图、散点图等。

二、JavaScript代码JavaScript是一种用于网页前端开发的脚本语言,在网页交互和动态效果方面具有突出优势。

以下是一些常用的JavaScript代码片段:1. 页面元素操作:使用document对象的getElementById或querySelector方法获取页面元素,并通过修改其属性或样式实现交互效果。

2. 表单验证:使用正则表达式对用户输入的表单数据进行验证,确保数据的合法性。

3. AJAX请求:使用XMLHttpRequest对象发送异步请求,与服务器进行数据交换,实现无刷新更新页面内容。

三、SQL代码SQL是一种用于管理和操作关系型数据库的语言。

以下是一些常用的SQL代码片段:1. 表创建:使用CREATE TABLE语句创建数据库表,并定义表的字段名和数据类型。

2. 数据查询:使用SELECT语句从数据库中检索数据,并使用WHERE子句过滤结果。

3. 数据更新:使用UPDATE语句修改数据库中的数据,并使用SET 子句指定要更新的字段和值。

四、Java代码Java是一种广泛应用于企业级应用开发的编程语言。

java 常用代码样版

java 常用代码样版

java 常用代码样版在Java开发领域中,开发人员常常需要为业务需求编写各种代码,包括实现算法、数据库访问、网络通信等等。

为了提高开发效率以及代码的可读性,我们需要学会使用一些常用代码样板,这样可以避免重复的工作,也提高了代码的可维护性。

下面,我将为大家介绍几个常用的Java代码样板:一、单例模式样板```public class Singleton {private static Singleton instance = null;private Singleton() {}public static Singleton getInstance(){if(instance == null) {instance = new Singleton();}return instance;}}```二、静态工厂样板```public class StaticFactory {public static Product getProduct(String type) {if (type.equals("productA")) {return new ProductA();} else if (type.equals("productB")) {return new ProductB();} else {return null;}}}```三、工厂方法样板```public interface Factory {public Product getProduct();}public class ProductAFactory implements Factory { public Product getProduct() {return new ProductA();}}public class ProductBFactory implements Factory { public Product getProduct() {return new ProductB();}}```四、代理模式样板```public interface Subject {public void request();}public class RealSubject implements Subject {public void request() {System.out.println("真实对象的请求");}}public class Proxy implements Subject {private RealSubject realSubject;public Proxy() {}public void request() {if(realSubject == null) {realSubject = new RealSubject();}preRequest();realSubject.request();postRequest();}private void preRequest() {System.out.println("请求前的处理...");}private void postRequest() {System.out.println("请求后的处理...");}}```五、观察者模式样板```public interface Observer {public void update();}public class ConcreteObserver implements Observer { public void update() {System.out.println("接收到通知,开始更新自己..."); }}public interface Subject {public void attach(Observer observer);public void detach(Observer observer);public void notifyObservers();}public class ConcreteSubject implements Subject {private List<Observer> observers = newArrayList<Observer>();public void attach(Observer observer) {observers.add(observer);}public void detach(Observer observer) {observers.remove(observer);}public void notifyObservers() {for (Observer observer : observers) {observer.update();}}}```六、策略模式样板```public interface Strategy {public void algorithm();}public class ConcreteStrategyA implements Strategy { public void algorithm() {System.out.println("使用算法A");}}public class ConcreteStrategyB implements Strategy { public void algorithm() {System.out.println("使用算法B");}}public class Context {private Strategy strategy;public Context(Strategy strategy) {this.strategy = strategy;}public void setStrategy(Strategy strategy) {this.strategy = strategy;}public void run() {strategy.algorithm();}}```以上就是几个常用的Java代码样板,这些样板代码不仅可以帮助开发人员提高开发效率,同时也提高了代码的可读性和可维护性。

java 常用 代码

java 常用 代码

java 常用代码Java是一种广泛应用于软件开发的编程语言,具有简单易学、跨平台、面向对象等特点。

在Java的开发过程中,有一些常用的代码片段,可以帮助程序员提高开发效率和代码质量。

本文将介绍一些常见的Java常用代码片段。

一、变量声明和赋值在Java中,变量的声明和赋值是非常常见的操作。

声明变量可以使用如下代码片段:```java数据类型变量名;```其中,数据类型可以是Java的基本数据类型,如int、double、boolean等,也可以是引用类型,如String、List等。

变量名则是开发者自定义的变量名称。

变量的赋值可以使用如下代码片段:```java变量名 = 值;```其中,值可以是直接量,也可以是其他变量的值。

二、条件语句在Java的开发中,经常需要根据条件来执行不同的代码逻辑。

条件语句可以使用如下代码片段:```javaif (条件) {// 条件成立时执行的代码} else {// 条件不成立时执行的代码}```其中,条件可以是一个布尔表达式,表示判断的条件。

if语句的后面可以跟上else语句,用于处理条件不成立时的逻辑。

三、循环语句循环语句在Java的开发过程中也是非常常用的。

循环语句可以使用如下代码片段:```javafor (初始化; 条件; 更新) {// 循环体}```其中,初始化是循环开始时执行的语句;条件是循环执行的条件;更新是每次循环结束后执行的语句。

循环体则是需要重复执行的代码。

四、方法定义和调用在Java中,方法是一组可以重复使用的代码块。

方法的定义和调用可以使用如下代码片段:```java修饰符返回类型方法名(参数列表) {// 方法体return 返回值;}```其中,修饰符可以是public、private等,用于控制方法的访问权限;返回类型是方法执行后的返回值类型;方法名是开发者自定义的方法名称;参数列表是方法的输入参数;方法体是方法的具体实现;return语句用于返回方法的返回值。

JAVASCRITP对象和函数难点整理

JAVASCRITP对象和函数难点整理

5、clearInterval()取消由setInterval()设置的时间间隔6、clearTimeout()取消由setTimeout()设置的计时(计时必须赋值给某个变量)7、confirm()创建包含OK和Cancel两个按钮的对话框,参数为对话框文本,点击OK返回true,点击Cancel返回false。

8、Date:这个对象表示时间,用以下方法可以创建日期对象:var the_date=new Date();//不初始化,当前日期和时间var the_date=new Date("month dd,yyyy");//month是月份的名称,如Januaryvar the_date=new Date("month dd,yyyy hh:mm:ss");var the_date=new Date("yy,mm,dd");var the_date=new Date("milliseconds");//毫秒取得日期和时间的方法getFullYear()//返回四位数字的年getMonth()//返回0-11表示的月,0表示JanuarygetDate()//返回以1-31表示月中的天getDay()//返回以0-6表示周中的天,0表示SundaygetHours()//返回以0-23表示的小时getMinutes()//返回以0-59表示的分钟getSeconds()//返回以0-59表示的秒getTime()//返回以毫秒计的当前时间,0表示1970、1、100:00:00设置日期和时间的方法:getDay()换为setYear()其余的与上边的一一对应,setYear()//设置年,如果介于1900-1999之间使用后两位数,否则使用四位数,如the_date.setYear(2012);有问题的getYear()处理方法:var the_date=new Date();var the_year=the_date.getYear();if(the_year<1000){the_year=the_year+1900;}取得UTC日期和时间的方法:设置UTC日期和时间的方法:9、Document:窗口的document对象中保存着该窗口的网页上所有的HTML元素属性:alinkColor当单击一个链接时链接的颜色anchors[]只读:所有锚对象数组applets[]只读:文档中存储所有小程序的数组bgColor页面的背景颜色body网页的body元素cookie与文档关联的HTML cookiedocumentElement只读:XML文件的根元素domain网页的域名embeds[]只读:embeds[]数组fgColor默认的字体颜色forms[]存储文档中所有表单的数组Images[]存储文档中所有图像的数组lastModified只读字符串,保存着用户最后修改文档的日期linkColor链接的默认颜色links[]存储文档中所有超链接的数组referrer只读字符串,包含引导到当前页面的超链接的域名styleSheets[]只读:所有style元素的数组title包含文档的标题URL文档的URLvlinkColor访问过的链接颜色,链接一经写入则不能再修改方法:close()在向文档中写入内容结束时可以使用这个方法createAttribute()创建一个以参数(字符串)命名的XML属性createElement()创建一个以参数(字符串)命名的XML元素createTextNode()创建一个nodeValue等于该参数(字符串)的文本节点getElementById()返回文档中id等于提供的字符串参数的元素getElementByName()返回文档中name属性设为指定字符串参数的元素数组getElementByTagName()返回具有指定名称的元素数组open()如果使用write()和writeln()方法写入网页之前,需要先清除网页的内容则使用该方法。

Java工程师必备的15个java代码

Java工程师必备的15个java代码
}
} 4.将 String 型转换成 Date 型,格式化日期
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class Test {
/** * @param args * @throws ParseException */
//以MYSQL数据库为例 String driverClass = "com.mysql.jdbc.Driver"; Connection conn = null; public static void main(String[] args) throws ParseException, FileNotFoundException, ClassNotFoundException, SQLException, IOException {
Properties props = new Properties();//实例化properties对象 props.load(fis);//加载输入流 String url = props.getProperty("db.url");//读取配置文件 String userName = props.getProperty("erNaem");//读取配置文件 String password = props.getProperty("db.password");//读取配置文件 Class.forName(driverClass); conn = DriverManager.getConnection(url,userName,password);

javascript常用代码大全-网页设计HTMLCSS

javascript常用代码大全-网页设计HTMLCSS

javas‎c ript‎常用代码‎大全-网页‎设计,HT‎M LCSS‎//打‎开模式对话‎框fu‎n ctio‎n dos‎e lect‎u ser(‎t xtid‎){ ‎‎‎s trfe‎a ture‎s="di‎a logw‎i dth=‎500px‎;dial‎o ghei‎g ht=3‎60px;‎c ente‎r=yes‎;midd‎l e=ye‎s ;he‎l p=n o‎;stat‎u s=no‎;scro‎l l=no‎";‎‎v ar u‎r l,st‎r retu‎r n;‎‎ u‎r l="s‎e luse‎r.asp‎x";‎‎‎‎s trre‎t urn=‎w indo‎w.sho‎w moda‎l dial‎o g(ur‎l,,st‎r feat‎u res)‎;‎}‎//‎返回模式对‎话框的值‎func‎t ion ‎o kbtn‎_oncl‎i ck()‎{‎v ar c‎o mmst‎r=; ‎‎‎‎wind‎o w.re‎t urnv‎a lue=‎c omms‎t r;‎‎ w‎i ndow‎.clos‎e() ;‎}‎全屏幕打开‎ie 窗‎口va‎r win‎w idth‎=scre‎e n.av‎a ilwi‎d th ;‎var‎winh‎e ight‎=scre‎e n.av‎a ilhe‎i ght-‎20;‎w indo‎w.ope‎n("ma‎i n.as‎p x","‎s urve‎y wind‎o w","‎t oolb‎a r=no‎,widt‎h="+ ‎w inwi‎d th ‎+",he‎i ght=‎" + wi‎n heig‎h t +‎",top‎=0,le‎f t=0,‎s crol‎l bars‎=yes,‎r esiz‎a ble=‎y es,c‎e nter‎:yes,‎s tatu‎s bars‎=yes"‎); b‎r eak ‎//脚本‎中中使用x‎m lf‎u ncti‎o n in‎i tial‎i ze()‎{‎var ‎x mldo‎c‎v ar x‎s ldoc‎‎ xml‎d oc =‎new ‎a ctiv‎e xobj‎e ct(m‎i cros‎o ft.x‎m ldom‎)‎x mldo‎c.asy‎n c = ‎f alse‎;‎xs‎l doc ‎= new‎acti‎v exob‎j ect(‎m icro‎s oft.‎x mldo‎m)‎xsld‎o c.as‎y nc =‎fals‎e;‎xm‎l doc.‎l oad(‎"tree‎.xml"‎)‎x sldo‎c.loa‎d("tr‎e e.xs‎l")‎‎fo‎l dert‎r ee.i‎n nerh‎t ml =‎xmld‎o c.do‎c umen‎t elem‎e nt.t‎r ansf‎o rmno‎d e(xs‎l doc)‎}‎一、‎验证类‎1、数字验‎证内‎1.1 ‎整数‎1.2 ‎大于0的整‎数(用于‎传来的id‎的验证) ‎1.‎3负整数‎的验证‎ 1.4‎整数不能‎大于ima‎x‎1.5 整‎数不能小于‎i min ‎2、时间‎类‎2.1 短‎时间,形如‎(13:‎04:06‎)‎2.2 短‎日期,形如‎(200‎3-12-‎05)‎ 2.3‎长时间,‎形如 (2‎003-1‎2-05 ‎13:04‎:06) ‎2.‎4只有年‎和月。

javascript实用代码大全

javascript实⽤代码⼤全//取得控件得绝对位置(1)<script language="javascript">function getoffset(e){var t=e.offsetTop;var l=e.offsetLeft;while(e=e.offsetParent){t+=e.offsetTop;l+=e.offsetLeft;}var rec = new Array(1);rec[0] = t;rec[1] = l;return rec}</script>//获得控件的绝对位置(2)oRect = obj.getBoundingClientRect();oRect.leftoRect.//最⼩化,最⼤化,关闭<object id=min classid="clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11"><param name="Command" value="Minimize"></object><object id=max classid="clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11"><param name="Command" value="Maximize"></object><OBJECT id=close classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11"><PARAM NAME="Command" value="Close"></OBJECT><input type=button value=最⼩化 onclick=min.Click()><input type=button value=最⼤化 onclick=max.Click()><input type=button value=关闭 onclick=close.Click()>//光标停在⽂字最后<script language="javascript">function cc(){var e = event.srcElement;var r =e.createTextRange();r.moveStart('character',e.value.length);r.collapse(true);r.select();}</script><input type=text name=text1 value="123" onfocus="cc()">//页⾯进⼊和退出的特效进⼊页⾯<meta http-equiv="Page-Enter" content="revealTrans(duration=x, transition=y)">推出页⾯<meta http-equiv="Page-Exit" content="revealTrans(duration=x, transition=y)">这个是页⾯被载⼊和调出时的⼀些特效。

Java中常用的代码汇总

Java中常⽤的代码汇总1. 字符串有整型的相互转换String a = String.valueOf(2); //integer to numeric stringint i = Integer.parseInt(a); //numeric string to an int2. 向⽂件末尾添加内容BufferedWriter out = null;try {out = new BufferedWriter(new FileWriter(”filename”, true));out.write(”aString”);} catch (IOException e) {// error processing code} finally {if (out != null) {out.close();}}3. 得到当前⽅法的名字String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();4. 转字符串到⽇期java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);或者是:SimpleDateFormat format = new SimpleDateFormat( "dd.MM.yyyy" );Date date = format.parse( myString );5. 使⽤JDBC链接Oraclepublic class OracleJdbcTest{String driverClass = "oracle.jdbc.driver.OracleDriver";Connection con;public void init(FileInputStream fs) throws ClassNotFoundException, SQLException, FileNotFoundException, IOException {Properties props = new Properties();props.load(fs);String url = props.getProperty("db.url");String userName = props.getProperty("er");String password = props.getProperty("db.password");Class.forName(driverClass);con=DriverManager.getConnection(url, userName, password);}public void fetch() throws SQLException, IOException{PreparedStatement ps = con.prepareStatement("select SYSDATE from dual");ResultSet rs = ps.executeQuery();while (rs.next()){// do the thing you do}rs.close();ps.close();}public static void main(String[] args){OracleJdbcTest test = new OracleJdbcTest();test.init();test.fetch();}}6. 把 Java util.Date 转成 sql.Datejava.util.Date utilDate = new java.util.Date();java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());7. 使⽤NIO进⾏快速的⽂件拷贝public static void fileCopy( File in, File out )throws IOException{FileChannel inChannel = new FileInputStream( in ).getChannel();FileChannel outChannel = new FileOutputStream( out ).getChannel();try{// inChannel.transferTo(0, inChannel.size(), outChannel); // original -- apparently has trouble copying large files on Windows // magic number for Windows, 64Mb - 32Kb)int maxCount = (64 * 1024 * 1024) - (32 * 1024);long size = inChannel.size();long position = 0;while ( position < size ){position += inChannel.transferTo( position, maxCount, outChannel );}}finally{if ( inChannel != null ){inChannel.close();}if ( outChannel != null ){outChannel.close();}}}8. 创建图⽚的缩略图private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)throws InterruptedException, FileNotFoundException, IOException{// load image from filenameImage image = Toolkit.getDefaultToolkit().getImage(filename);MediaTracker mediaTracker = new MediaTracker(new Container());mediaTracker.addImage(image, 0);mediaTracker.waitForID(0);// use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());// determine thumbnail size from WIDTH and HEIGHTdouble thumbRatio = (double)thumbWidth / (double)thumbHeight;int imageWidth = image.getWidth(null);int imageHeight = image.getHeight(null);double imageRatio = (double)imageWidth / (double)imageHeight;if (thumbRatio < imageRatio) {thumbHeight = (int)(thumbWidth / imageRatio);} else {thumbWidth = (int)(thumbHeight * imageRatio);}// draw original image to thumbnail image object and// scale it to the new size on-the-flyBufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);Graphics2D graphics2D = thumbImage.createGraphics();graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);// save thumbnail image to outFilenameBufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);quality = Math.max(0, Math.min(quality, 100));param.setQuality((float)quality / 100.0f, false);encoder.setJPEGEncodeParam(param);encoder.encode(thumbImage);out.close();}9.创建 JSON 格式的数据import org.json.JSONObject;......JSONObject json = new JSONObject();json.put("city", "Mumbai");json.put("country", "India");...String output = json.toString();...10. 使⽤iText JAR⽣成PDFimport java.io.File;import java.io.FileOutputStream;import java.io.OutputStream;import java.util.Date;import com.lowagie.text.Document;import com.lowagie.text.Paragraph;import com.lowagie.text.pdf.PdfWriter;public class GeneratePDF {public static void main(String[] args) {try {OutputStream file = new FileOutputStream(new File("C:\\Test.pdf")); Document document = new Document();PdfWriter.getInstance(document, file);document.open();document.add(new Paragraph("Hello Kiran"));document.add(new Paragraph(new Date().toString()));document.close();file.close();} catch (Exception e) {e.printStackTrace();}}}11. HTTP 代理设置System.getProperties().put("http.proxyHost", "someProxyURL"); System.getProperties().put("http.proxyPort", "someProxyPort"); System.getProperties().put("http.proxyUser", "someUserName"); System.getProperties().put("http.proxyPassword", "somePassword"); 12. 单实例Singleton ⽰例public class SimpleSingleton {private static SimpleSingleton singleInstance = new SimpleSingleton(); //Marking default constructor private//to avoid direct instantiation.private SimpleSingleton() {}//Get instance for class SimpleSingletonpublic static SimpleSingleton getInstance() {return singleInstance;}}13. 抓屏程序import java.awt.Dimension;import java.awt.Rectangle;import java.awt.Robot;import java.awt.Toolkit;import java.awt.image.BufferedImage;import javax.imageio.ImageIO;import java.io.File;...public void captureScreen(String fileName) throws Exception {Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Rectangle screenRectangle = new Rectangle(screenSize);Robot robot = new Robot();BufferedImage image = robot.createScreenCapture(screenRectangle); ImageIO.write(image, "png", new File(fileName));}...14. 列出⽂件和⽬录File dir = new File("directoryName");String[] children = dir.list();if (children == null) {// Either dir does not exist or is not a directory} else {for (int i=0; i < children.length; i++) {// Get filename of file or directoryString filename = children[i];}}// It is also possible to filter the list of returned files.// This example does not return any files that start with `.'.FilenameFilter filter = new FilenameFilter() {public boolean accept(File dir, String name) {return !name.startsWith(".");}};children = dir.list(filter);// The list of files can also be retrieved as File objectsFile[] files = dir.listFiles();// This filter only returns directoriesFileFilter fileFilter = new FileFilter() {public boolean accept(File file) {return file.isDirectory();}};files = dir.listFiles(fileFilter);15. 创建ZIP和JAR⽂件import java.util.zip.*;import java.io.*;public class ZipIt {public static void main(String args[]) throws IOException {if (args.length < 2) {System.err.println("usage: java ZipIt Zip.zip file1 file2 file3");System.exit(-1);}File zipFile = new File(args[0]);if (zipFile.exists()) {System.err.println("Zip file already exists, please try another");System.exit(-2);}FileOutputStream fos = new FileOutputStream(zipFile);ZipOutputStream zos = new ZipOutputStream(fos);int bytesRead;byte[] buffer = new byte[1024];CRC32 crc = new CRC32();for (int i=1, n=args.length; i < n; i++) {String name = args[i];File file = new File(name);if (!file.exists()) {System.err.println("Skipping: " + name);continue;}BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));crc.reset();while ((bytesRead = bis.read(buffer)) != -1) {crc.update(buffer, 0, bytesRead);}bis.close();// Reset to beginning of input streambis = new BufferedInputStream(new FileInputStream(file));ZipEntry entry = new ZipEntry(name);entry.setMethod(ZipEntry.STORED);entry.setCompressedSize(file.length());entry.setSize(file.length());entry.setCrc(crc.getValue());zos.putNextEntry(entry);while ((bytesRead = bis.read(buffer)) != -1) {zos.write(buffer, 0, bytesRead);}bis.close();}zos.close();}}16. 解析/读取XML ⽂件XML⽂件<?xml version="1.0"?><students><student><name>John</name><grade>B</grade><age>12</age></student><student><name>Mary</name><grade>A</grade><age>11</age></student><student><name>Simon</name><grade>A</grade><age>18</age></student></students>Java代码<span style="font-family:Arial;font-size:14px;">package net.viralpatel.java.xmlparser; import java.io.File;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class XMLParser {public void getAllUserNames(String fileName) {try {DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilder db = dbf.newDocumentBuilder();File file = new File(fileName);if (file.exists()) {Document doc = db.parse(file);Element docEle = doc.getDocumentElement();// Print root element of the documentSystem.out.println("Root element of the document: "+ docEle.getNodeName());NodeList studentList = docEle.getElementsByTagName("student");// Print total student elements in documentSystem.out.println("Total students: " + studentList.getLength());if (studentList != null && studentList.getLength() > 0) {for (int i = 0; i < studentList.getLength(); i++) {Node node = studentList.item(i);if (node.getNodeType() == Node.ELEMENT_NODE) {System.out.println("=====================");Element e = (Element) node;NodeList nodeList = e.getElementsByTagName("name");System.out.println("Name: "+ nodeList.item(0).getChildNodes().item(0).getNodeValue());nodeList = e.getElementsByTagName("grade");System.out.println("Grade: "+ nodeList.item(0).getChildNodes().item(0).getNodeValue());nodeList = e.getElementsByTagName("age");System.out.println("Age: "+ nodeList.item(0).getChildNodes().item(0).getNodeValue());}}} else {System.exit(1);}}} catch (Exception e) {System.out.println(e);}}public static void main(String[] args) {XMLParser parser = new XMLParser();parser.getAllUserNames("c:\\test.xml");}}17. 把 Array 转换成 Mapimport java.util.Map;import ng.ArrayUtils;public class Main {public static void main(String[] args) {String[][] countries = { { "United States", "New York" }, { "United Kingdom", "London" }, { "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } };Map countryCapitals = ArrayUtils.toMap(countries);System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));System.out.println("Capital of France is " + countryCapitals.get("France"));}}18. 发送邮件import javax.mail.*;import javax.mail.internet.*;import java.util.*;public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException {boolean debug = false;//Set the host smtp addressProperties props = new Properties();props.put("mail.smtp.host", "");// create some properties and get the default SessionSession session = Session.getDefaultInstance(props, null);session.setDebug(debug);// create a messageMessage msg = new MimeMessage(session);// set the from and to addressInternetAddress addressFrom = new InternetAddress(from);msg.setFrom(addressFrom);InternetAddress[] addressTo = new InternetAddress[recipients.length];for (int i = 0; i < recipients.length; i++){addressTo[i] = new InternetAddress(recipients[i]);}msg.setRecipients(Message.RecipientType.TO, addressTo);// Optional : You can also set your custom headers in the Email if you Wantmsg.addHeader("MyHeaderName", "myHeaderValue");// Setting the Subject and Content Typemsg.setSubject(subject);msg.setContent(message, "text/plain");Transport.send(msg);}19. 发送代数据的HTTP 请求import java.io.BufferedReader;import java.io.InputStreamReader;import .URL;public class Main {public static void main(String[] args) {try {URL my_url = new URL("/");BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));String strTemp = "";while(null != (strTemp = br.readLine())){System.out.println(strTemp);}} catch (Exception ex) {ex.printStackTrace();}}}20. 改变数组的⼤⼩/*** Reallocates an array with a new size, and copies the contents* of the old array to the new array.* @param oldArray the old array, to be reallocated.* @param newSize the new array size.* @return A new array with the same contents.*/private static Object resizeArray (Object oldArray, int newSize) {int oldSize = ng.reflect.Array.getLength(oldArray);Class elementType = oldArray.getClass().getComponentType();Object newArray = ng.reflect.Array.newInstance(elementType,newSize);int preserveLength = Math.min(oldSize,newSize);if (preserveLength > 0)System.arraycopy (oldArray,0,newArray,0,preserveLength);return newArray;}// Test routine for resizeArray().public static void main (String[] args) {int[] a = {1,2,3};a = (int[])resizeArray(a,5);a[3] = 4;a[4] = 5;for (int i=0; i<a.length; i++)System.out.println (a[i]);}以上所述就是本⽂的全部内容了,希望⼤家能够喜欢。

java常用代码(20条案例)

java常用代码(20条案例)1. 输出Hello World字符串public class Main {public static void main(String[] args) {// 使用System.out.println()方法输出字符串"Hello World"System.out.println("Hello World");}}2. 定义一个整型变量并进行赋值public class Main {public static void main(String[] args) {// 定义一个名为num的整型变量并将其赋值为10int num = 10;// 使用System.out.println()方法输出变量num的值System.out.println(num);}}3. 循环打印数字1到10public class Main {public static void main(String[] args) {// 使用for循环遍历数字1到10for (int i = 1; i <= 10; i++) {// 使用System.out.println()方法输出每个数字System.out.println(i);}}}4. 实现输入输出import java.util.Scanner;public class Main {public static void main(String[] args) {// 创建一个Scanner对象scanner,以便接受用户的输入Scanner scanner = new Scanner(System.in);// 使用scanner.nextLine()方法获取用户输入的字符串String input = scanner.nextLine();// 使用System.out.println()方法输出输入的内容System.out.println("输入的是:" + input);}}5. 实现条件分支public class Main {public static void main(String[] args) {// 定义一个整型变量num并将其赋值为10int num = 10;// 使用if语句判断num是否大于0,如果是,则输出"这个数是正数",否则输出"这个数是负数"if (num > 0) {System.out.println("这个数是正数");} else {System.out.println("这个数是负数");}}}6. 使用数组存储数据public class Main {public static void main(String[] args) {// 定义一个整型数组nums,其中包含数字1到5int[] nums = new int[]{1, 2, 3, 4, 5};// 使用for循环遍历数组for (int i = 0; i < nums.length; i++) {// 使用System.out.println()方法输出每个数组元素的值System.out.println(nums[i]);}}}7. 打印字符串长度public class Main {public static void main(String[] args) {// 定义一个字符串变量str并将其赋值为"HelloWorld"String str = "Hello World";// 使用str.length()方法获取字符串的长度,并使用System.out.println()方法输出长度System.out.println(str.length());}}8. 字符串拼接public class Main {public static void main(String[] args) {// 定义两个字符串变量str1和str2,并分别赋值为"Hello"和"World"String str1 = "Hello";String str2 = "World";// 使用"+"号将两个字符串拼接成一个新字符串,并使用System.out.println()方法输出拼接后的结果System.out.println(str1 + " " + str2);}}9. 使用方法进行多次调用public class Main {public static void main(String[] args) {// 定义一个名为str的字符串变量并将其赋值为"Hello World"String str = "Hello World";// 调用printStr()方法,打印字符串变量str的值printStr(str);// 调用add()方法,计算两个整数的和并输出结果int result = add(1, 2);System.out.println(result);}// 定义一个静态方法printStr,用于打印字符串public static void printStr(String str) {System.out.println(str);}// 定义一个静态方法add,用于计算两个整数的和public static int add(int a, int b) {return a + b;}}10. 使用继承实现多态public class Main {public static void main(String[] args) {// 创建一个Animal对象animal,并调用move()方法Animal animal = new Animal();animal.move();// 创建一个Dog对象dog,并调用move()方法Dog dog = new Dog();dog.move();// 创建一个Animal对象animal2,但其实际指向一个Dog对象,同样调用move()方法Animal animal2 = new Dog();animal2.move();}}// 定义一个Animal类class Animal {public void move() {System.out.println("动物在移动");}}// 定义一个Dog类,继承自Animal,并重写了move()方法class Dog extends Animal {public void move() {System.out.println("狗在奔跑");}}11. 输入多个数并求和import java.util.Scanner;public class Main {public static void main(String[] args) {// 创建一个Scanner对象scanner,以便接受用户的输入Scanner scanner = new Scanner(System.in);// 定义一个整型变量sum并将其赋值为0int sum = 0;// 使用while循环持续获取用户输入的整数并计算总和,直到用户输入为0时结束循环while (true) {System.out.println("请输入一个整数(输入0退出):");int num = scanner.nextInt();if (num == 0) {break;}sum += num;}// 使用System.out.println()方法输出总和System.out.println("所有输入的数的和为:" + sum);}}12. 判断一个年份是否为闰年import java.util.Scanner;public class Main {public static void main(String[] args) {// 创建一个Scanner对象scanner,以便接受用户的输入Scanner scanner = new Scanner(System.in);// 使用scanner.nextInt()方法获取用户输入的年份System.out.println("请输入一个年份:");int year = scanner.nextInt();// 使用if语句判断年份是否为闰年,如果是,则输出"是闰年",否则输出"不是闰年"if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {System.out.println(year + "年是闰年");} else {System.out.println(year + "年不是闰年");}}}13. 使用递归实现斐波那契数列import java.util.Scanner;public class Main {public static void main(String[] args) {// 创建一个Scanner对象scanner,以便接受用户的输入Scanner scanner = new Scanner(System.in);// 使用scanner.nextInt()方法获取用户输入的正整数nSystem.out.println("请输入一个正整数:");int n = scanner.nextInt();// 使用for循环遍历斐波那契数列for (int i = 1; i <= n; i++) {System.out.print(fibonacci(i) + " ");}}// 定义一个静态方法fibonacci,使用递归计算斐波那契数列的第n项public static int fibonacci(int n) {if (n <= 2) {return 1;} else {return fibonacci(n - 1) + fibonacci(n - 2);}}}14. 输出九九乘法表public class Main {public static void main(String[] args) {// 使用两层for循环打印九九乘法表for (int i = 1; i <= 9; i++) {for (int j = 1; j <= i; j++) {System.out.print(j + "*" + i + "=" + (i * j) + "\t");}System.out.println();}}}15. 使用try-catch-finally处理异常import java.util.Scanner;public class Main {public static void main(String[] args) {// 创建一个Scanner对象scanner,以便接受用户的输入Scanner scanner = new Scanner(System.in);try {// 使用scanner.nextInt()方法获取用户输入的整数a和bSystem.out.println("请输入两个整数:");int a = scanner.nextInt();int b = scanner.nextInt();// 对a进行除以b的运算int result = a / b;// 使用System.out.println()方法输出结果System.out.println("计算结果为:" + result);} catch (ArithmeticException e) {// 如果除数为0,会抛出ArithmeticException异常,捕获异常并使用System.out.println()方法输出提示信息System.out.println("除数不能为0");} finally {// 使用System.out.println()方法输出提示信息System.out.println("程序结束");}}}16. 使用集合存储数据并遍历import java.util.ArrayList;import java.util.List;public class Main {public static void main(String[] args) {// 创建一个名为list的List集合,并添加多个字符串元素List<String> list = new ArrayList<>();list.add("Java");list.add("Python");list.add("C++");list.add("JavaScript");// 使用for循环遍历List集合并使用System.out.println()方法输出每个元素的值for (int i = 0; i < list.size(); i++) {System.out.println(list.get(i));}}}17. 使用Map存储数据并遍历import java.util.HashMap;import java.util.Map;public class Main {public static void main(String[] args) {// 创建一个名为map的Map对象,并添加多组键值对Map<Integer, String> map = new HashMap<>();map.put(1, "Java");map.put(2, "Python");map.put(3, "C++");map.put(4, "JavaScript");// 使用for-each循环遍历Map对象并使用System.out.println()方法输出每个键值对的值for (Map.Entry<Integer, String> entry :map.entrySet()) {System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());}}}18. 使用lambda表达式进行排序import java.util.ArrayList;import java.util.Collections;import parator;import java.util.List;public class Main {public static void main(String[] args) {// 创建一个名为list的List集合,并添加多个字符串元素List<String> list = new ArrayList<>();list.add("Java");list.add("Python");list.add("C++");list.add("JavaScript");// 使用lambda表达式定义Comparator接口的compare()方法,按照字符串长度进行排序Comparator<String> stringLengthComparator = (s1, s2) -> s1.length() - s2.length();// 使用Collections.sort()方法将List集合进行排序Collections.sort(list, stringLengthComparator);// 使用for-each循环遍历List集合并使用System.out.println()方法输出每个元素的值for (String str : list) {System.out.println(str);}}}19. 使用线程池执行任务import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Main {public static void main(String[] args) {// 创建一个名为executor的线程池对象,其中包含2个线程ExecutorService executor =Executors.newFixedThreadPool(2);// 使用executor.execute()方法将多个Runnable任务加入线程池中进行执行executor.execute(new MyTask("任务1"));executor.execute(new MyTask("任务2"));executor.execute(new MyTask("任务3"));// 调用executor.shutdown()方法关闭线程池executor.shutdown();}}// 定义一个MyTask类,实现Runnable接口,用于代表一个任务class MyTask implements Runnable {private String name;public MyTask(String name) { = name;}@Overridepublic void run() {System.out.println("线程" +Thread.currentThread().getName() + "正在执行任务:" + name);try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("线程" +Thread.currentThread().getName() + "完成任务:" + name);}}20. 使用JavaFX创建图形用户界面import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import yout.StackPane;import javafx.stage.Stage;public class Main extends Application {@Overridepublic void start(Stage primaryStage) throws Exception { // 创建一个Button对象btn,并设置按钮名称Button btn = new Button("点击我");// 创建一个StackPane对象pane,并将btn添加到pane中StackPane pane = new StackPane();pane.getChildren().add(btn);// 创建一个Scene对象scene,并将pane作为参数传入Scene scene = new Scene(pane, 200, 100);// 将scene设置为primaryStage的场景primaryStage.setScene(scene);// 将primaryStage的标题设置为"JavaFX窗口"primaryStage.setTitle("JavaFX窗口");// 调用primaryStage.show()方法显示窗口primaryStage.show();}public static void main(String[] args) { launch(args);}}。

JAVA代码大全


. 命令行参数 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
方 法
. 输入方法演示 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. 统计学生成绩 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. ASCII 码表 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. 乘法表 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. Course . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. 整数栈 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
System.out.println(”Hello, World!”);
}
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

javascript 常用代码大全(3)打开模式对话框返回模式对话框的值全屏幕打开 IE 窗口脚本中中使用xml一、验证类1、数字验证内2、时间类3、表单类4、字符类5、浏览器类6、结合类二、功能类1、时间与相关控件类2、表单类3、打印类4、事件类5、网页设计类6、树型结构。

7、无边框效果的制作8、连动下拉框技术9、文本排序10,画图类,含饼、柱、矢量贝滋曲线11,操纵客户端注册表类12,DIV层相关(拖拽、显示、隐藏、移动、增加)13,TABLAE相关(客户端动态增加行列,模拟进度条,滚动列表等) 14,各种object classid=>相关类,如播放器,flash与脚本互动等16, 刷新/模拟无刷新异步调用类(XMLHttp或iframe,frame)针对javascript的几个对象的扩充函数function checkBrowser(){this.ver=navigator.appVersionthis.dom=document.getElementById?1:0this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom)?1:0;this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom)?1:0;this.ie4=(document.all && !this.dom)?1:0;this.ns5=(this.dom && parseInt(this.ver) >= 5) ?1:0;this.ns4=(yers && !this.dom)?1:0;this.mac=(this.ver.indexOf('Mac') > -1) ?1:0;this.ope=(erAgent.indexOf('Opera')>-1);this.ie=(this.ie6 || this.ie5 || this.ie4)this.ns=(this.ns4 || this.ns5)this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns5 || this.ns4 || this.mac || this.ope)this.nbw=(!this.bw)return this;}/*******************************************日期函数扩充*******************************************//*===========================================//转换成大写日期(中文)===========================================*/Date.prototype.toCase = function(){var digits= new Array('零','一','二','三','四','五','六','七','八','九','十','十一','十二');var unit= new Array('年','月','日','点','分','秒');var year= this.getYear() + "";var index;var output="";////////得到年for (index=0;index<year.length;index++ ){output += digits[parseInt(year.substr(index,1))];}output +=unit[0];///////得到月output +=digits[this.getMonth()] + unit[1];///////得到日switch (parseInt(this.getDate() / 10)){case 0:output +=digits[this.getDate() % 10];break;case 1:output +=digits[10] + ((this.getDate() %10)>0?digits[(this.getDate() % 10)]:"");break;case 2:case 3:output +=digits[parseInt(this.getDate() / 10)] + digits[10] + ((this.getDate() % 10)>0?digits[(this.getDate() % 10)]:""); default:break;}output +=unit[2];///////得到时switch (parseInt(this.getHours() / 10)){case 0:output +=digits[this.getHours() % 10];break;case 1:output +=digits[10] + ((this.getHours() %10)>0?digits[(this.getHours() % 10)]:"");break;case 2:output +=digits[parseInt(this.getHours() / 10)] + digits[10] +((this.getHours() % 10)>0?digits[(this.getHours() % 10)]:""); break;}output +=unit[3];if(this.getMinutes()==0&&this.getSeconds()==0){output +="整";return output;}///////得到分switch (parseInt(this.getMinutes() / 10)){case 0:output +=digits[this.getMinutes() % 10];break;case 1:output +=digits[10] + ((this.getMinutes() %10)>0?digits[(this.getMinutes() % 10)]:"");break;case 2:case 3:case 4:case 5:output +=digits[parseInt(this.getMinutes() / 10)] + digits[10] + ((this.getMinutes() % 10)>0?digits[(this.getMinutes() % 10)]:""); break;}output +=unit[4];if(this.getSeconds()==0){output +="整";return output;}///////得到秒switch (parseInt(this.getSeconds() / 10)){case 0:output +=digits[this.getSeconds() % 10];break;case 1:output +=digits[10] + ((this.getSeconds() %10)>0?digits[(this.getSeconds() % 10)]:"");break;case 2:case 3:case 4:case 5:output +=digits[parseInt(this.getSeconds() / 10)] + digits[10] + ((this.getSeconds() % 10)>0?digits[(this.getSeconds() % 10)]:""); break;}output +=unit[5];return output;}/*===========================================//转换成农历===========================================*/Date.prototype.toChinese = function(){//暂缺}/*===========================================//是否是闰年===========================================*/Date.prototype.isLeapYear = function(){return(0==this.getYear()%4&&((this.getYear()%100!=0)||(this.getYear()%400== 0)));}/*===========================================//获得该月的天数===========================================*/Date.prototype.getDayCountInMonth = function(){var mon = new Array(12);mon[0] = 31; mon[1] = 28; mon[2] = 31; mon[3] = 30; mon[4] = 31; mon[5] = 30;mon[6] = 31; mon[7] = 31; mon[8] = 30; mon[9] = 31; mon[10] = 30; mon[11] = 31;if(0==this.getYear()%4&&((this.getYear()%100!=0)||(this.getYear()%400 ==0))&&this.getMonth()==2){return 29;}else{return mon[this.getMonth()];}}/*===========================================//日期比较===========================================*/pare = function(objDate){if(typeof(objDate)!="object" && objDate.constructor != Date){return -2;}var d = this.getTime() - objDate.getTime();if(d>0){return 1;}else if(d==0){return 0;}else{return -1;}}/*===========================================//格式化日期格式===========================================*/Date.prototype.Format = function(formatStr){var str = formatStr;str=str.replace(/yyyy|YYYY/,this.getFullYear());str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():"0" + (this.getYear() % 100));str=str.replace(/MM/,this.getMonth()>9?this.getMonth().toString():"0" + this.getMonth());str=str.replace(/M/g,this.getMonth());str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():"0 " + this.getDate());str=str.replace(/d|D/g,this.getDate());str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString(): "0" + this.getHours());str=str.replace(/h|H/g,this.getHours());str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString() :"0" + this.getMinutes());str=str.replace(/m/g,this.getMinutes());str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toStrin g():"0" + this.getSeconds());str=str.replace(/s|S/g,this.getSeconds());return str;}/*===========================================//由字符串直接实例日期对象===========================================*/Date.prototype.instanceFromString = function(str){return new Date("2004-10-10".replace(/-/g, "\/"));}/*===========================================//得到日期年月日等加数字后的日期===========================================*/Date.prototype.dateAdd = function(interval,number){var date = this;switch(interval){case "y" :date.setFullYear(date.getFullYear()+number);return date;case "q" :date.setMonth(date.getMonth()+number*3);return date;case "m" :date.setMonth(date.getMonth()+number);return date;case "w" :date.setDate(date.getDate()+number*7);return date;case "d" :date.setDate(date.getDate()+number);return date;case "h" :date.setHours(date.getHours()+number);return date;case "m" :date.setMinutes(date.getMinutes()+number);return date;case "s" :date.setSeconds(date.getSeconds()+number);return date;default :date.setDate(d.getDate()+number);return date;}}/*===========================================//计算两日期相差的日期年月日等===========================================*/Date.prototype.dateDiff = function(interval,objDate){//暂缺}/*******************************************数字函数扩充*******************************************//*===========================================//转换成中文大写数字===========================================*/Number.prototype.toChinese = function(){var num = this;if(!/^\d*(\.\d*)?$/.test(num)){alert("Number is wrong!"); return "Number is wrong!";}var AA = new Array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖");var BB = new Array("","拾","佰","仟","萬","億","点","");var a = (""+ num).replace(/(^0*)/g, "").split("."), k = 0, re = "";for(var i=a[0].length-1; i>=0; i--){switch(k){case 0 : re = BB[7] + re; break;case 4 : if(!new RegExp("0{4}\\d{"+(a[0].length-i-1) +"}$").test(a[0]))re = BB[4] + re; break;case 8 : re = BB[5] + re; BB[7] = BB[5]; k = 0; break;}if(k%4 == 2 && a[0].charAt(i+2) != 0 &&a[0].charAt(i+1) == 0) re = AA[0] + re;if(a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] +BB[k%4] + re; k++;}if(a.length>1) //加上小数部分(如果有小数部分){re += BB[6];for(var i=0; i<a[1].length; i++) re +=AA[a[1].charAt(i)];}return re;}/*===========================================//保留小数点位数===========================================*/Number.prototype.toFixed=function(len){if(isNaN(len)||len==null){len = 0;}else{if(len<0){len = 0;}}return Math.round(this * Math.pow(10,len)) / Math.pow(10,len); }/*===========================================//转换成大写金额===========================================*/Number.prototype.toMoney = function(){// Constants:var MAXIMUM_NUMBER = 99999999999.99;// Predefine the radix characters and currency symbols for output: var CN_ZERO= "零";var CN_ONE= "壹";var CN_TWO= "贰";var CN_THREE= "叁";var CN_FOUR= "肆";var CN_FIVE= "伍";var CN_SIX= "陆";var CN_SEVEN= "柒";var CN_EIGHT= "捌";var CN_NINE= "玖";var CN_TEN= "拾";var CN_HUNDRED= "佰";var CN_THOUSAND = "仟";var CN_TEN_THOUSAND= "万";var CN_HUNDRED_MILLION= "亿";var CN_SYMBOL= "";var CN_DOLLAR= "元";var CN_TEN_CENT = "角";var CN_CENT= "分";var CN_INTEGER= "整";// Variables:var integral; // Represent integral part of digit number.var decimal; // Represent decimal part of digit number.var outputCharacters; // The output result.var parts;var digits, radices, bigRadices, decimals;var zeroCount;var i, p, d;var quotient, modulus;if (this > MAXIMUM_NUMBER){return "";}// Process the coversion from currency digits to characters:// Separate integral and decimal parts before processing coversion:parts = (this + "").split(".");if (parts.length > 1){integral = parts[0];decimal = parts[1];// Cut down redundant decimal digits that are after the second. decimal = decimal.substr(0, 2);}else{integral = parts[0];decimal = "";}// Prepare the characters corresponding to the digits:digits= new Array(CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE, CN_SIX, CN_SEVEN, CN_EIGHT, CN_NINE);radices= new Array("", CN_TEN, CN_HUNDRED, CN_THOUSAND);bigRadices= new Array("", CN_TEN_THOUSAND, CN_HUNDRED_MILLION); decimals= new Array(CN_TEN_CENT, CN_CENT);// Start processing:outputCharacters = "";// Process integral part if it is larger than 0:if (Number(integral) > 0){zeroCount = 0;for (i = 0; i < integral.length; i++){p = integral.length - i - 1;d = integral.substr(i, 1);quotient = p / 4;modulus = p % 4;if (d == "0"){zeroCount++;}else{if (zeroCount > 0){outputCharacters += digits[0];}zeroCount = 0;outputCharacters += digits[Number(d)] + radices[modulus]; }if (modulus == 0 && zeroCount < 4){outputCharacters += bigRadices[quotient];}}outputCharacters += CN_DOLLAR;}// Process decimal part if there is:if (decimal != ""){for (i = 0; i < decimal.length; i++){d = decimal.substr(i, 1);if (d != "0"){outputCharacters += digits[Number(d)] + decimals[i];}}}// Confirm and return the final output string:if (outputCharacters == ""){outputCharacters = CN_ZERO + CN_DOLLAR;}if (decimal == ""){outputCharacters += CN_INTEGER;}outputCharacters = CN_SYMBOL + outputCharacters;return outputCharacters;}Number.prototype.toImage = function(){var num = Array("#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x5,0x5,0x5,0xF}","#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0x4,0x4,0x4,0x4,0x4}","#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x4,0xF,0x1,0xF}","#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x4,0xF,0x4,0xF}","#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0x5,0x5,0xF,0x4,0x4}","#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x1,0xF,0x4,0xF}","#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x1,0xF,0x5,0xF}","#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x4,0x4,0x4,0x4}","#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x5,0xF,0x5,0xF}","#define t_width 3\n#define t_height 5\nstatic char t_bits[] = {0xF,0x5,0xF,0x4,0xF}");var str = this + "";var iIndexvar result=""for(iIndex=0;iIndex<str.length;iIndex++){result +="<img src='javascript:" & num(iIndex) & "'">}return result;}/*******************************************其他函数扩充*******************************************//*===========================================//验证类函数===========================================*/function IsEmpty(obj){obj=document.getElementsByName(obj).item(0);if(Trim(obj.value)==""){if(obj.disabled==false && obj.readOnly==false){obj.focus();}return true;}else{return false;}}/*===========================================//无模式提示对话框===========================================*/function modelessAlert(Msg){window.showModelessDialog("javascript:alert(\""+escape(Msg)+"\") ;window.close();","","status:no;resizable:no;help:no;dialogHeight:hei ght:30px;dialogHeight:40px;");}/*===========================================//页面里回车到下一控件的焦点===========================================*/function Enter2Tab(){var e = document.activeElement;if(e.tagName == "INPUT" &&(e.type == "text" ||e.type == "password" ||e.type == "checkbox" ||e.type == "radio") ||e.tagName == "SELECT"){if(window.event.keyCode == 13){window.event.keyCode = 9;}}}////////打开此功能请取消下行注释//document.onkeydown = Enter2Tab;function ViewSource(url){window.location = 'view-source:'+ url;}///////禁止右键document.oncontextmenu = function() { return false;}/*******************************************字符串函数扩充*******************************************//*===========================================//去除左边的空格===========================================*/String.prototype.LTrim = function(){return this.replace(/(^\s*)/g, "");}String.prototype.Mid = function(start,len) {if(isNaN(start)&&start<0){return "";}if(isNaN(len)&&len<0){return "";}return this.substring(start,len);}/*=========================================== //去除右边的空格=========================================== */String.prototype.Rtrim = function(){return this.replace(/(\s*$)/g, "");}/*=========================================== //去除前后空格=========================================== */String.prototype.Trim = function(){return this.replace(/(^\s*)|(\s*$)/g, "");}/*===========================================//得到左边的字符串===========================================*/String.prototype.Left = function(len){if(isNaN(len)||len==null){len = this.length;}else{if(parseInt(len)<0||parseInt(len)>this.length) {len = this.length;}}return this.substring(0,len);}/*===========================================//得到右边的字符串===========================================*/String.prototype.Right = function(len){if(isNaN(len)||len==null){len = this.length;}else{if(parseInt(len)<0||parseInt(len)>this.length){len = this.length;}}return this.substring(this.length-len,this.length); }/*===========================================//得到中间的字符串,注意从0开始===========================================*/String.prototype.Mid = function(start,len){if(isNaN(start)||start==null){start = 0;}else{if(parseInt(start)<0){start = 0;}}if(isNaN(len)||len==null){len = this.length;}else{if(parseInt(len)<0){len = this.length;}}return this.substring(start,start+len);}/*=========================================== //在字符串里查找另一字符串:位置从0开始=========================================== */String.prototype.InStr = function(str){if(str==null){str = "";}return this.indexOf(str);}/*=========================================== //在字符串里反向查找另一字符串:位置0开始=========================================== */String.prototype.InStrRev = function(str) {if(str==null){str = "";}return stIndexOf(str);}/*===========================================//计算字符串打印长度===========================================*/String.prototype.LengthW = function(){return this.replace(/[^\x00-\xff]/g,"**").length; }/*===========================================//是否是正确的IP地址===========================================*/String.prototype.isIP = function(){var reSpaceCheck = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;if (reSpaceCheck.test(this)){this.match(reSpaceCheck);if (RegExp.$1 <= 255 && RegExp.$1 >= 0&& RegExp.$2 <= 255 && RegExp.$2 >= 0&& RegExp.$3 <= 255 && RegExp.$3 >= 0&& RegExp.$4 <= 255 && RegExp.$4 >= 0){return true;}else{return false;}}else{return false;}}/*===========================================//是否是正确的长日期===========================================*/String.prototype.isDate = function(){var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})(\d{1,2}):(\d{1,2}):(\d{1,2})$/);if(r==null){return false;}var d = new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);return(d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d. getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);}/*===========================================//是否是手机===========================================*/String.prototype.isMobile = function(){return /^0{0,1}13[0-9]{9}$/.test(this);}/*===========================================//是否是邮件===========================================*/String.prototype.isEmail = function(){return /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(this);}/*===========================================//是否是邮编(中国)===========================================*/String.prototype.isZipCode = function(){return /^[\\d]{6}$/.test(this);}/*===========================================//是否是有汉字===========================================*/String.prototype.existChinese = function(){//[\u4E00-\u9FA5]為漢字﹐[\uFE30-\uFFA0]為全角符號return /^[\x00-\xff]*$/.test(this);}/*===========================================//是否是合法的文件名/目录名===========================================*/String.prototype.isFileName = function(){return !/[\\\/\*\?\|:"<>]/g.test(this);}/*===========================================//是否是有效链接===========================================*/String.Prototype.isUrl = function(){return /^http:\/\/([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$/.test(this); }/*===========================================//是否是有效的身份证(中国)===========================================*/String.prototype.isIDCard = function(){var iSum=0;var info="";var sId = this;var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"};if(!/^\d{17}(\d|x)$/i.test(sId)){return false;}sId=sId.replace(/x$/i,"a");//非法地区if(aCity[parseInt(sId.substr(0,2))]==null){return false;}var sBirthday=sId.substr(6,4)+"-"+Number(sId.substr(10,2))+"-"+Number(sId.substr(12,2));var d=new Date(sBirthday.replace(/-/g,"/"))//非法生日if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" +d.getDate())){return false;}for(var i = 17;i>=0;i--){iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 - i),11);}if(iSum%11!=1){return false;}return true;}/*===========================================//是否是有效的电话号码(中国)===========================================*/String.prototype.isPhoneCall = function(){return /(^[0-9]{3,4}\-[0-9]{3,8}$)|(^[0-9]{3,8}$)|(^\([0-9]{3,4}\)[0-9]{3,8}$)|(^0{0,1}13[0-9]{9}$)/.test(this); }/*=========================================== //是否是数字=========================================== */String.prototype.isNumeric = function(flag) {//验证是否是数字if(isNaN(this)){return false;}switch(flag){case null://数字case "":return true;case "+"://正数return/(^\+?|^\d?)\d*\.?\d+$/.test(this); case "-"://负数return/^-\d*\.?\d+$/.test(this);case "i"://整数return/(^-?|^\+?|\d)\d+$/.test(this);case "+i"://正整数return/(^\d+$)|(^\+?\d+$)/.test(this);case "-i"://负整数return/^[-]\d+$/.test(this);case "f"://浮点数return/(^-?|^\+?|^\d?)\d*\.\d+$/.test(this); case "+f"://正浮点数return/(^\+?|^\d?)\d*\.\d+$/.test(this); case "-f"://负浮点数return/^[-]\d*\.\d$/.test(this);default://缺省return true;}}/*===========================================//转换成全角===========================================*/String.prototype.toCase = function(){var tmp = "";for(var i=0;i<this.length;i++){if(this.charCodeAt(i)>0&&this.charCodeAt(i)<255){tmp += String.fromCharCode(this.charCodeAt(i)+65248); }else{tmp += String.fromCharCode(this.charCodeAt(i));}}return tmp}/*===========================================//对字符串进行Html编码===========================================*/String.prototype.toHtmlEncode = function{var str = this;str=str.replace("&","&amp;");str=str.replace("<","&lt;");str=str.replace(">","&gt;");str=str.replace("'","&apos;");str=str.replace("\"","&quot;");return str;}qqdao(青青岛)精心整理的输入判断js函数关键词:字符串判断,字符串处理,字串判断,字串处理//'*********************************************************// ' Purpose: 判断输入是否为整数字// ' Inputs: String// ' Returns: True, False//'********************************************************* function onlynumber(str){var i,strlength,tempchar;str=CStr(str);if(str=="") return false;strlength=str.length;for(i=0;i<strlength;i++){tempchar=str.substring(i,i+1);if(!(tempchar==0||tempchar==1||tempchar==2||tempchar== 3||tempchar==4||tempchar==5||tempchar==6||tempchar==7||tempchar==8||t empchar==9)){alert("只能输入数字");return false;}}return true;}//'*********************************************************//'*********************************************************// ' Purpose: 判断输入是否为数值(包括小数点)// ' Inputs: String// ' Returns: True, False//'********************************************************* function IsFloat(str){ var tmp;var temp;var i;tmp =str;if(str=="") return false;for(i=0;i<tmp.length;i++){temp=tmp.substring(i,i+1);if((temp>='0'&& temp<='9')||(temp=='.')){} //check input in 0-9 and '.'else { return false;}}return true;}//'*********************************************************// ' Purpose: 判断输入是否为电话号码// ' Inputs: String// ' Returns: True, False//'********************************************************* function isphonenumber(str){var i,strlengh,tempchar;str=CStr(str);if(str=="") return false;strlength=str.length;for(i=0;i<strlength;i++){tempchar=str.substring(i,i+1);if(!(tempchar==0||tempchar==1||tempchar==2||tempchar== 3||tempchar==4||tempchar==5||tempchar==6||tempchar==7||tempchar==8||t empchar==9||tempchar=='-')){alert("电话号码只能输入数字和中划线");return(false);}}return(true);}//'*********************************************************//'*********************************************************// ' Purpose: 判断输入是否为Email// ' Inputs: String// ' Returns: True, False//'********************************************************* function isemail(str){var bflag=trueif (str.indexOf("'")!=-1) {bflag=false}if (str.indexOf("@")==-1) {bflag=false}else if(str.charAt(0)=="@"){bflag=false}return bflag}//'*********************************************************// ' Purpose: 判断输入是否含有为中文。

相关文档
最新文档