Java编程 经验技巧汇总

CuterCorley
• 阅读 1473

1.JSONArray数组如何循环遍历

package xxx;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) {
    /*author:命运的信徒
     * date:2019/5/18
     */
    String str ="[{'otitle':'会','source':'7'},{'otitle':'不会','source':'3'}]";
    //1.把字符串类型的json数组对象转化JSONArray
    JSONArray json=JSONArray.fromObject(str);
    //2、循环遍历这个数组
     for(int i=0;i<json.size();i++){
         //3、把里面的对象转化为JSONObject
          JSONObject job = json.getJSONObject(i);   
          // 4、把里面想要的参数一个个用.属性名的方式获取到
          System.out.println(job.get("otitle")+":"+job.get("source")) ; 
          }
    }
}

可参考https://blog.csdn.net/qq_37591637/article/details/90319229

2.生成UNIX时间戳(精度:秒)

public class Test {
    public static void main(String[] args) {
        //生成随机时间
        long offset = Timestamp.valueOf("2012-01-01 00:00:00").getTime();
        long end = Timestamp.valueOf("2013-01-01 00:00:00").getTime();
        long diff = end - offset + 1;
        Timestamp rand = new Timestamp(offset + (long)(Math.random() * diff));
        System.out.println(rand);
        //下面两个是一样的结果,都是当前时间(UNIX时间戳)
        System.out.println(System.currentTimeMillis() / 1000);
        System.out.println(Calendar.getInstance().getTimeInMillis() / 1000);

    }
}

3.随机生成时间

Random   rand   =   new   Random();
SimpleDateFormat   format   =   new   SimpleDateFormat( "yyyy-MM-dd ");
Calendar   cal   =   Calendar.getInstance();
cal.set(1900,   0,   1);
long   start   =   cal.getTimeInMillis();
cal.set(2008,   0,   1);
long   end   =   cal.getTimeInMillis();
for(int   i   =   0;   i   <   10;   i++)   {
Date   d   =   new   Date(start   +   (long)(rand.nextDouble()   *   (end   -   start)));
System.out.println(format.format(d));
}

4.随机生成颜色

方式一: 给定范围获得随机颜色

private Color getRandColor(int fc, int bc) {  
     Random random = new Random();  
    if (fc > 255)  
       fc = 255;  
    if (bc > 255)  
       bc = 255;  
    int r = fc + random.nextInt(bc - fc);  
    int g = fc + random.nextInt(bc - fc);  
    int b = fc + random.nextInt(bc - fc);  
    return new Color(r, g, b);  
   }

getRandColor(200, 250)

方式二:生成随机十六进制颜色代码

 //随机生成颜色代码
    public String getColor(){
        //红色
        String red;
        //绿色
        String green;
        //蓝色
        String blue;
        //生成随机对象
        Random random = new Random();
        //生成红色颜色代码
        red = Integer.toHexString(random.nextInt(256)).toUpperCase();
        //生成绿色颜色代码
        green = Integer.toHexString(random.nextInt(256)).toUpperCase();
        //生成蓝色颜色代码
        blue = Integer.toHexString(random.nextInt(256)).toUpperCase();

        //判断红色代码的位数
        red = red.length()==1 ? "0" + red : red ;
        //判断绿色代码的位数
        green = green.length()==1 ? "0" + green : green ;
        //判断蓝色代码的位数
        blue = blue.length()==1 ? "0" + blue : blue ;
        //生成十六进制颜色值
        String color = "#"+red+green+blue;
        return color;
    }

5.java正则表达式取出匹配字符串

举例如下,


package javatest;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaTest
{
    public static void main( String args[] ){

      // 指定模式
      String line = "This order was placed for QT3000! OK?";
      String pattern = "(\\D*)(\\d+)(.*)";

      // 创建 Pattern 对象
      Pattern r = Pattern.compile(pattern);

      // 创建 matcher 对象
      Matcher m = r.matcher(line);
      if (m.find( )) {
         System.out.println("Found value: " + m.group(1) );
         System.out.println("Found value: " + m.group(2) );
         System.out.println("Found value: " + m.group(3) ); 
      } else {
         System.out.println("NO MATCH");
      }
   }
}

打印

Found value: This order was placed for QT
Found value: 3000
Found value: ! OK?

6.Java整数和字符串的相互转化

以下是把整形地i转化为字符串s,把Double、Float、Long与字符串操作的操作类似。

(1)把int转化为String

String s=""+i;
String s=Integer.toString(i);
String s=String.valueOf(i);

(2)把String转化为int型:

int i = Integer.intValue(s);
int i=Integer.parsenInt(s);
int i=Integer.valueOf(s).intValue();

(3)Integer转换成int:

Integer i = new Integer(10); 
int k = i.intValue();
//即Integer.intValue();

(4)int转换成Integer:

int i = 10;
Integer it = new Integer(i);

(5)String转换成Integer:

String str = "10";
Integer it = Integer.valueOf(str);

(6)Integer转换成String:

Integer it = new Integer(10);
String str = it.toString();

(8)String转换成BigDecimal:

BigDecimal bd = new BigDecimal(str);

7.获取当前时间日期字符串

使用Date类

package javatest;

/**
 *
 * @author Lenovo
 */
import java.text.SimpleDateFormat;
import java.util.Date;

public class JavaTest
{
    public static void main( String args[] ){

        Date d = new Date();
        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
        String str1 = date.format(d);
        SimpleDateFormat datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str2 = datetime.format(d);
        System.out.println(str1);
        System.out.println(str2);

   }
}

结果

2019-12-11
2019-12-11 11:21:21

8.生成指定范围的随机数

生成 MIN~MAX 之间的随机数:

Random rand = new Random();
int randNumber =rand.nextInt(MAX - MIN + 1) + MIN; // randNumber 将被赋值为一个 MIN 和 MAX 范围内的随机数

9.快速生成10位时间戳

Long newTime = System.currentTimeMillis();
String time = newTime.toString().substring(0, 10);

本文原文首发来自博客专栏Java专栏,由本人转发至https://www.helloworld.net/p/kdzhM1h0nCjb,其他平台均属侵权,可点击https://blog.csdn.net/CUFEECR/article/details/103341711查看原文,也可点击https://blog.csdn.net/CUFEECR浏览更多优质原创内容。

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
3个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
Java爬虫之JSoup使用教程
title:Java爬虫之JSoup使用教程date:201812248:00:000800update:201812248:00:000800author:mecover:https://imgblog.csdnimg.cn/20181224144920712(https://www.oschin
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
9个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这