现在的位置: 首页 > 综合 > 正文

java经典小函数、细节积累

2013年10月19日 ⁄ 综合 ⁄ 共 12221字 ⁄ 字号 评论关闭
Java经典小函数、细节积累
--目录--


--Content--

1、输入年月日,计算该天是今年的第几天

     三部分,1、主函数。 2、输入月份和年份输入精确的该月总共有多少天。3、判断是否为闰年

  System.out.println("输入一个日期,格式:yyyy-mm-dd,来判断这是这一年的第几天");
  String gotdate=sc.next();
  String condate="";
  int year,month,day;
  if(gotdate.matches("[1-2][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]")){//输入控制,bug:输入2000-02-29这里是允许的
   year=Integer.parseInt(gotdate.substring(0,4));
   month=Integer.parseInt(gotdate.substring(5,7));
   day=Integer.parseInt(gotdate.substring(8,10));
   condate=year+"年"+month+"月"+day+"日";
   System.out.println(condate);
   int days=0;
   Array array=new Array();
   for(int i=1;i<month;i++){
    days+=array.getDays(array.isLeapYear(year), i);
   }
   days+=day;
   System.out.println(condate+"是今年的第"+days+"天");
  }else System.out.println("日期格式不正确!");
  public int getDays(boolean isLeap,int m){//精确闰年返回传入的月份的总天数
  
  if(m==1||m==3||m==5||m==7||m==8||m==10)
   return 31;
  else if(m==4||m==6||m==9||m==11)
   return 30;
  else if(isLeap&&m==2)return 28;
  else if(!isLeap&&m==2)return 29;
  else return -1;
 }
 public boolean isLeapYear(int y){//判断传入年份是不是闰年
  if((y%4==0&&y%100!=0)||y%400==0){
   System.out.println("今年是闰年,二月有28天");
   return true;}
  else return false;
 }

2、质因数的分解:

  System.out.println("下面输入一个数,来给它分解质因数:");
  ArrayList<Integer>list=new ArrayList<Integer>();
  a=sc.nextInt();
  int b;
  boolean hasfinished=false;
  String outputString=a+"=";
  while(!hasfinished){
   for(b=2;b<=a/2;b++){
    if(a%b==0){
     a=a/b;
     list.add(b);
     break;
    }
    if(b>a/2-1)
     hasfinished=true;
   }
  }
  list.add(a);
  for (int k : list) {
   outputString=outputString+k+"*";
  }
  outputString=outputString.substring(0,outputString.length()-1);
  System.out.println(outputString);

3、取得当前时间的年月日时分秒

        说明:java.util.Date的getDay()等方法已过期,采用如上方法才行。     其中取得月份,查看api可知,Calendar是使用的**标准,该标准的月份从0开始:1月返回0,二月返回1。

  Calendar calendar=Calendar.getInstance();//java.util.Calendar
  int d=calendar.get(Calendar.DAY_OF_MONTH);
  int m=calendar.get(Calendar.MONTH)+1;//1月是零,从零开始。
  int y=calendar.get(Calendar.YEAR);
  int h=calendar.get(Calendar.HOUR);
  int min=calendar.get(Calendar.MINUTE);
  int s=calendar.get(Calendar.SECOND);

4、二进制的数字串类型转换成十进制整型

  public int BinaryStringtoInt(String s){//传入二进制的字符串,转成十进制整形。0110111--
  int oneBit=-1;
  int allBit=0;
  int len=s.length();
  for(int i=0;i<len;i++){
   oneBit=Integer.parseInt(s.charAt(i)+"");
   System.out.println(s.length());
   allBit+=oneBit<<(len-1-i);
  }
  return allBit;
 }
5、File文件的修改
说明:一行一行(或一个字符数组)的读取原文件,然后修改,然后写入另一个文件中

import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException;

public class HelloWorld {  public static void main(String[] args) {   File file=new File("D:/ex/test.txt");//The original file   File file2=new File("D:/ex/Copiedtest.txt");//The modified file   File temp=null;   if(!file.exists()){//If the original file dose not exist,create it and write something in it;    temp=new File(file.getParent());    temp.mkdirs();    try {     file.createNewFile();     FileWriter fWriter=new FileWriter(file);     fWriter.write("Hello World");     fWriter.flush();     fWriter.close();    } catch (IOException e) {     e.printStackTrace();    }   }   if(!file2.exists()){//Create the modified file;    temp=new File(file2.getParent());    temp.mkdirs();    try {     file2.createNewFile();    } catch (IOException e) {     e.printStackTrace();    }   }      try {    FileReader fReader=new FileReader(file);    BufferedReader bfr=new BufferedReader(fReader);    FileWriter fWriter=new FileWriter(file2);    BufferedWriter bfw =new BufferedWriter(fWriter);        String mark="";    while(mark!=null){     mark=bfr.readLine();//Can also use bfr.read(char[] args) for the huge file that contains just one line;     System.out.println(mark);     if(mark!=null){//This is the modification operation      mark=mark.replace('l', 'L');      System.out.println(mark);      bfw.write(mark);      bfw.flush();     }    }    bfw.close();//Closing operations are highly recommended    fWriter.close();    bfr.close();    fReader.close();   } catch (FileNotFoundException e) {    e.printStackTrace();   } catch (IOException e) {    e.printStackTrace();   }  } }

6、Socket通信
需要提醒的两点:BufferedReader方法的read和readLine()方法在接收不到信息时也会阻塞;read()跟print()对应,readLine()跟println()对应。
    Server:

package com.elf.threadsocket;

import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket;

public class ServerSocketNum {  public static void main(String[] args) throws IOException{   System.out.println("#################This is the Server##################");   ServerSocket ssk=new ServerSocket(8888);   String gotString="";   Socket socket=ssk.accept();   BufferedReader bfrd=new BufferedReader(new InputStreamReader(socket.getInputStream()));   PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));;   try {    System.out.println("Server Started...");        System.out.println("Somebody logged,and I'm waiting for his request....");     gotString=bfrd.readLine();     System.out.println("I got:"+gotString);    String[] arr=gotString.split(" ");    for(int i=0;i<arr.length;i++){     pWriter.println(arr[i]);//That println() is related to readline() is as print() related to read();    }    pWriter.println("exit");    try {     /*      * Even if I sleep for a while,the client will wait for me.because he has a method readline.      */     for(int i=0;i<10;i++){      Thread.sleep(500);       System.out.println(i);     }         } catch (InterruptedException e) {     // TODO Auto-generated catch block     e.printStackTrace();    }    pWriter.flush();    System.out.println("I resonsed:"+gotString);    System.out.println("response finished...");   } catch (IOException e) {    e.printStackTrace();   }   finally{    ssk.close();    System.out.println("Server Closed...");   }  } }

    Client:

package com.elf.threadsocket;

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException;

public class Client {  public static void main(String[] args) throws UnknownHostException, IOException {   System.out.println("***********I'm the Client*****************");   Socket socket=new Socket("127.0.0.1", 8888);   System.out.println("Client Started...");   BufferedReader bfr;   PrintWriter pWriter;   String response="";   try {    bfr=new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));    pWriter=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "GBK"));    /*     * Request to the server     */    pWriter.println("aa bb cc");    pWriter.flush();        /*     * Get the Response from the server     */    System.out.println("If the server won't response,Can I Block??");    while(true){     response=bfr.readLine();     System.out.println("I got the response:"+response);//That println() is related to readline() is as print() related to read();     if("exit".equals(response)){      break;     }    }    System.out.println("I got the response:"+response);    System.out.println("If I couldnot get the response from the server,I would have blocked!Because I have a readLine() method.");   } catch (UnknownHostException e) {    // TODO Auto-generated catch block    e.printStackTrace();   } catch (IOException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }finally{    socket.close();    System.out.println("Client Stopped...");   }  }

}

7、Oracle中sql分页查询
--查询scott.emp表中按deptno排序的第7-10行--
--由于rownum不能做>运算,故采用倒置的方法--
--为保险起见,使用时请删除注释--
select* from emp order by deptno asc;--查询出全部的用来对比--
select * from(--S3:从S2的查询结果中选取前3行
       select * from (--S2:把S1的查询结果按deptno倒置--
              select * from emp order by deptno--S1:查询出前10行--
       )where rownum<=10 order by deptno desc
)
where rownum <=3 order by deptno asc;
8、在没有js的情况下,完整地验证输入长度为10的字符串格式是否为日期
	/**
	 * TODO 判断是否为闰年
	 * @param 
	 * @return
	 */
	public boolean isLeapYear(int y) {// 判断传入年份是不是闰年
		if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) {
			return true;
		} else
			return false;
	}

	/**
	 * TODO 在没有js的情况下,精确验证长度为10的字符串是否为日期格式的。
	 * @param 长度为10位的 String型date
	 * @return 各种错误信息
	 */
	public String VisDate(String date){
		date=date.trim();
		if(date.length()!=10) return "日期格式应为10位字符串类型";
		String year=date.substring(0, 4);
		String op1=date.substring(4,5);
		String month=date.substring(5,7);
		String op2=date.substring(7, 8);
		String day=date.substring(8,10);
		if(!(op1.equals(op2)))return "不合法的日期";
		String regex="[0-2][0-9]{3}";
		if(!(year.matches(regex))) return "日期年份不合法";
		regex="[0-1][0-9]";
		if(!(month.matches(regex))) return "日期月份不合法";
		regex="[0-3][0-9]";
		if(!(day.matches(regex))) return "日期天数不合法";
		
		int y=Integer.parseInt(year);
		int m=Integer.parseInt(month);
		int d=Integer.parseInt(day);
		
		if(m==1||m==3||m==5||m==7||m==8||m==10||m==12){
			if(d>31||d<1) return "该月没有那一天";
		}
		if(m==4||m==6||m==9||m==11){
			if(d>30||d<1) return "该月没有那一天";
		}
		
		boolean isLeap=isLeapYear(y);
		if(isLeap&&m==2){
			if(d>28||d<0) return "本年是闰年,二月最多28天";
		}
		if(!isLeap&&m==2){
			if(d>29||d<0) return "该月没有那一天";
		}
		return "true";
	}

hibernate生成的DAO同一张表实现多个字段查询并且不破坏MVC架构
//这是DAO文件里加入的函数
 public List findByProperties(ArrayList<String> pnames,ArrayList<Object> values){
	    	String debugString="finding Eqptyp instance with properties: "+pnames.get(0)+",value:"+values.get(0);
	    	String queryString="from Eqptyp as model where model.";
	    	queryString=queryString+ pnames.get(0)+"=?";
	    	
	    	int size=pnames.size();
	    	Object[]val=new Object[size];
	    	val[0]=values.get(0);
	    	for(int i=1;i<size;i++){
	    		queryString=queryString+"and model."+pnames.get(i)+"=?";
	    		debugString = debugString+pnames.get(i)+",value:"+values.get(i);
	    		val[i]=values.get(i);
	    		
	    		System.out.println("debugString:"+debugString);
	    		System.out.println("queryString:"+queryString);
	    	}
	    	log.debug(debugString);
	    	try {
	           
	   		 return getHibernateTemplate().find(queryString,val);
	         } catch (RuntimeException re) {
	            log.error("find by property name failed", re);
	            throw re;
	         }
	    }

//这是service里的调用方法
	public EqptypDto selet(EqptypDto etdto) {
		// TODO Auto-generated method stub
		ArrayList<String> names = new ArrayList<String>();
		ArrayList<Object> values = new ArrayList<Object>();
		
		ArrayList<Eqptyp> list=null;
		try{
			if("".equals(etdto.getTypId())&&"0".equals(etdto.getTypCommTyp())&&"0".equals(etdto.getTypPosTyp())&&"0".equals(etdto.getTypKeyTyp())){//全空选择
				list=(ArrayList<Eqptyp>)etdao.findAll();
			}else{
				if (!"".equals(etdto.getTypId())) {//编号
					names.add("typId");
					values.add(etdto.getTypId());
				}
				if (!"0".equals(etdto.getTypCommTyp())) {// POS设备类型
					names.add("typCommTyp");
					values.add(etdto.getTypCommTyp());
				}
				if (!"0".equals(etdto.getTypPosTyp())) {// 终端类型(台式或手持)
					names.add("typPosTyp");
					values.add(etdto.getTypPosTyp());
				}
				if(!"0".equals(etdto.getTypKeyTyp())){//密码键盘
					names.add("typKeyTyp");
					values.add(etdto.getTypKeyTyp());
				}
					list =(ArrayList<Eqptyp>)etdao.findByProperties(names, values);
			}
		}catch (Exception e) {
			// TODO: handle exception
			etdto.setRst(ToolUtil.ERROR);
			e.printStackTrace();
			return etdto;
		}
		if(list.size()==0){
			etdto.setRst(ToolUtil.EMPTY);
		}else{
			etdto.setList(list);
			etdto.setRst(ToolUtil.RIGHT);
		}
		return etdto;
	}
10、   js脚本实现动态增删表格行TR,并为之添加不同的颜色,并验证
		function setTrColor(){
			var trs=document.getElementsByTagName("tr");
			for(var i=0;i<trs.length;i++){
				if(i%2==0)
				trs[i].style.backgroundColor="#d5fcf7";
			}
		}
		var index=1;
		function addone(){
			index=index+1;
			trId = parseInt(1000000000000000000*(Math.random()));//随机产生生成的tr的id,该id用于删除。
			tab=document.getElementById("tab1");
			tab.innerHTML=tab.innerHTML+"<tr id='tr"+trId+"'><td>"+index+"</td><td><input type='text' name='posId' /></td><td><input type='text' name='typId' /></td><td><input type='text' name='prodId' /></td><td><select name='posSts'><option value='0'>请选择</option><option value='1'>在库正常</option><option value='2'>在库损坏</option><option value='3'>不在库正常使用中</option><option value='4'>不在库冻结</option><option value='5'>不在库挂失</option></select></td><td><input type='text' value='' disabled /></td><td><a href='javascript:delone(tr"+trId+")'>去掉该行</a></td></tr>";
			setTrColor();
		}
		function delone(id){
			tab=document.getElementById("tab1");
			tab.removeChild(id);
		}
		
		function vali(form){
			var posId=form.posId;
			var typId=form.typId;
			var prodId=form.prodId;
			var posSts=form.posSts;
			var count=1;
			for(var i=0;i<posId.length;i++){
				if((posId[i].value==""&&typId[i].value==""&&prodId[i].value==""&&posSts[i].value=="0")||(posId[i].value!=""&&typId[i].value!=""&&prodId[i].value!=""&&posSts[i].value!="0")){
					count=count*1;
				}else {
				count=count*0;
					alert("对不起,要求[POS机编号][类型编号][厂商编号]和[Pos机状态]必须填");
					return false;
				}
			}
			if(count==1) {
				alert("true");
				return true;
			}
		}
标题11
代码区5
标题12
代码区5
标题13
代码区5
标题14
代码区5
标题15
代码区5
标题16
代码区5
标题17
代码区5
标题18
代码区5
标题19
代码区5
标题20
代码区5

抱歉!评论已关闭.