JAVA 一句话技巧

 

1.拆分字符串
遇到特殊字符,比如:对‘$’符号,就应该使用‘\\$’,后总结可以加个方括号如 "[.]"。

2.遍历HASHMAP
Iterator itr = map.keySet().itrator();
while(itr.hasNext())
{
    Object temp1 = itr.next();
    Object temp2 = tab.get(temp1);
}

3.日历操作
Calendar c = Canlendar.getInstance();
c.get(c.YEAR);//获取年份,其他同理
c.add(c.MONTH,-1);//上个月的日期
 
4.随机数
Random random = new Random();
int ran = random.nextInt(100);
注意:范围[0,100)

5.读取配置文件
对于ini 文件或者 properties文件,其实只要内容是 ds=dfjh或者 kd: ksadkf这种,就可以用
Properties pro = new Properties();
//pro.load (Main.class.getResourceAsStream("/test.properties"));或者
//pro.load (new FileInputStream ("test.properties"));
pro.getProperty ("test")

6.遍历vector
两种方式:
//        for (Enumeration e = v.elements ();e.hasMoreElements ();)
//        {
//             System.out.println (e.nextElement ().toString ());
//        }    
       Iterator item = v.iterator ();
       while(item.hasNext ())
       {
           System.out.println (item.next ().toString ());
       }

7.JAVA在WINDOWS下调用其他程序
try
{
    Process p = Runtime.getRuntime().exec("mspaint");
    p.waitFor();
}catch ...

8.获取键盘输入
BufferedReader input = new BufferedReader(new InputStream(System.in));
String s = input.readLine();

9.子类无参构造会隐式super(),若父类没有声明无参构造函数,而且有含参数构造函数,程序编译不通过。

10.命令提示符下,编译java文件 建议使用"javac -d . xxx.java" 能自动生成程序中的包。而运行只需要"java packname.mainclass".

11.使用 "pack200 x.gz y.jar"则将jar文件压缩成gz文件,对class文件压缩率极高,解压缩使用"unpack200 x.gz y.jar".

12.代码中'@'标记符号使用,例如@ Override 在方法前面,表示此方法是覆盖父类方法,那么在编译时会自动检查父类中是否有该方法。

13.周期性事件:

private java.util.Timer timer;
timer.schedule(new java.util.TimerTask()
{
   public void run()
   {
       //……要做的事
   }
},0,5*60*1000);
timer本身是多线程同步的,不需要自己启动线程。

14.介绍下JDK5.0 新特性枚举类型:
public class EnumDemo
{
 enum MyColors
 {
   red,
   black,
   blue,
   green,
   yellow
 };
 public static void main(String args[])
 {
    MyColors color = MyColors.red;
    //for 也是JDK 5中新特性
    for(MyColors option : color.values())
    {
      System.out.println(option);
    }
   switch(color)
   {
    case red:
         System.out.println("best color is "+color.red);
         break;
     default:
          System.out.println("What");
          break;
   }
 }
}
几点注意:1. enum不能写成局部变量。
      2. switch()参数为枚举常量。
      3. case 后red实际是 color.red(由于其机制强制省略color)而其他地方是不能直接用red的.

15.正则表达式:(检验邮箱)
   String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$" ;
   Pattern regex = Pattern.compile (check) ;
   Matcher matcher = regex.matcher (Emailname) ;
   boolean isMatched = matcher.matches () ;

16.序列化
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(byteOut);
out.writeObject(combo);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream in =new ObjectInputStream(byteIn);
JComboBox comb2 = (JComboBox)in.readObject();

17.数据库操作
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
Connection m_objConnection = DriverManager.getConnection (jdbc:odbc:smstransmitDB;uid=sa;pwd=leslie);
/*
Statement objStatement = m_objConnection.createStatement (ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
*/
String m_objDelSql = "delete from " + m_objTable +
" where " + m_objFldTagId + "=?";
PreparedStatement objStatement = m_objConnection.prepareStatement (m_objDelSql);
objStatement.setInt (1, objSms.id);
objStatement.execute ();
/*executeQuery()返回ResultSet结果*/


18.JAVA 截取小数位数
float a = 1234.5678f;
java.text.DecimalFormat df =new java.text.DecimalFormat("#.00");
String a=df.format(a);
System.out.println(a); //1234.56
//写#的是有值就写值,没值就不写
//写0的是有值就写值,没值就写0


19.大小写互换

public static void main (String[] args)

         Scanner sc = new Scanner (System.in); 
         sc.useDelimiter ("\n"); 
         String temp = sc.next (); 
         chang_two(temp); 
         sc.close ();
}

//大小写 互换
public staic void chang_two (String text)

      char tem [] = text.toCharArray (); 
      for (int i = 0; i <tem.length;i++) 
      { 
            if(tem[i]>=97&&tem[i]<=122) 
            { 
                  tem[i]=(char)(tem[i]-32);

              }else if (tem[i]>=65&&tem[i]<=90) 
            { 
                  tem[i]=(char)(tem[i]+32); 
            } 
      }

   System.out.println(new String (tem));
}
20.java中格式化输出数字

在实际工作中,常常需要设定数字的输出格式,如以百分比的形式输出,或者设定小数位数等,现稍微总结如下。
主要使用的类:java.text.DecimalFormat
1。实例化对象,可以用如下两种方法:
DecimalFormat df=(DecimalFormat)NumberFormat.getInstance();
DecimalFormat df1=(DecimalFormat) DecimalFormat.getInstance();
因为DecimalFormat继承自NumberFormat。
2。设定小数位数
系统默认小数位数为3,如:
DecimalFormat df=(DecimalFormat)NumberFormat.getInstance();
System.out.println(df.format(12.3456789));
输出:12.346
现在可以通过如下方法把小数为设为两位:
df.setMaximumFractionDigits(2);
System.out.println(df.format(12.3456789));
则输出为:12.35
3。将数字转化为百分比输出,有如下两种方法:
(1)
df.applyPattern("##.##%");
System.out.println(df.format(12.3456789));
System.out.println(df.format(1));
System.out.println(df.format(0.015));
输出分别为:1234.57% 100% 1.5%
(2)
df.setMaximumFractionDigits(2);
System.out.println(df.format(12.3456789*100)+"%");
System.out.println(df.format(1*100)+"%");
System.out.println(df.format(0.015*100)+"%");
输出分别为:
1,234.57% 100% 1.5%
4。设置分组大小
DecimalFormat df1=(DecimalFormat) DecimalFormat.getInstance();
df1.setGroupingSize(2);
System.out.println(df1.format(123456789));
输出:1,23,45,67,89
还可以通过df1.setGroupingUsed(false);来禁用分组设置,如:
DecimalFormat df1=(DecimalFormat) DecimalFormat.getInstance();
df1.setGroupingSize(2);
df1.setGroupingUsed(false);
System.out.println(df1.format(123456789));
输出:123456789
5。设置小数为必须为2位
DecimalFormat df2=(DecimalFormat) DecimalFormat.getInstance();
df2.applyPattern("0.00");
System.out.println(df2.format(1.2));
输出:1.20

21.遍历VECTOR

for(int i = 0; i<v.size ();i++)
{
System.out.println (v.elementAt (i));
}

22.关于instanceof

class A{

int a = 10;
void a(){
}
}
class B{
int b = 20;
void b(){
}
}
public class Ex_instanceOf extends A{

public static void main(String[] args) {
A b = new A();
System.out.println(b instanceof A);
}
}
以上代码会输出true,但是将代码System.out.println(b instanceof A);
改为System.out.println(b instanceof B);并不会输出false,而是不能通过编译请问怎么样才能达到输出false的效果呢!!!

答:
一般instanceof用在未知类型(比如Object)之间的比较。由于b显式定义为class A,而A与B之间显式没有继承关系,所以,编译器会报错。你把A b= new A();改成Object b = new A();就行了

23.虽然Scanner可以不用进行显示的声明异常,但是遇到非法的用户输入时程序就直接退出去了。这在实际的用户程序中是不行的,也就是说容错处理不好!所以建议还是用BufferedReader
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值