Java Cheatsheet

Hello, World.

public class learn {
    public static void main(String[] args){
        System.out.println("hi");
    }
}

 

Built-in data types:

int, double, boolean, char, String

 

类型转换:

字符串转为数字: 

        String s1 = "1234";
        String s2 = "1234.123";
        
        int a = Integer.parseInt(s1);
        double b = Double.parseDouble(s2);
        long c = Long.parseLong(s1);
        
        System.out.println(a); //1234
        System.out.println(b); //1234.123
        System.out.println(c); //1234

 

数字转换成字符串:

        double d = 123.4;
        String s = String.valueOf(d);
        System.out.println(s); //123.4

     s = Integer.toString(n); // int to string

 

字符串加数字, 生成字符串

"1234"+99 --> "123499"

 

Switch:

switch(day){
  case 0: System.out.println("Sun"); break;
  case 1: System.out.println("Mon"); break;
  
}

 

数组:

double[] b = new double[N];

 

Input:

Scanner in=new Scanner(System.in);
String readLine = in.nextLine();
System.out.println(readLine);

 

字符串长度:

s.length()

 

limits:

Integer.MAX_VALUE

 

二维数组:

type arrayName[ ][ ];
type [ ][ ]arrayName;

// 动态: 可以直接给每一维分配空间的!好腻害!
arrayName = new type[arrayLength1][arrayLength2];
int a[ ][ ] = new int[2][3];

 

EOF: Scanner 的 hasNext()函数

Scanner scan = new Scanner(System.in);
int count=1;
while(scan.hasNext()) {
    String s = scan.nextLine();
    System.out.println(count + " " + s);
    count++;
}

 

格式化输出:

https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

System.out.format("%08d%n", n);

 

static block:

Static initialization blocks are executed when the class is loaded, and you can initialize static variables in those blocks.

public class Solution {
    public static int B,H;static {
        Scanner sc = new Scanner(System.in);
        B = sc.nextInt();
        H = sc.nextInt();
    }
}

 

posted @ 2016-01-23 04:08  飞飞喵  阅读(804)  评论(0)    收藏  举报