Java 筆記

一路波折兜兜轉轉終於開始了海外的兩年求學生活,課程中不免俗地需要碰到後端語言因此在此記錄下Java相關的筆記

字符

Java 中將浮點數舍入到小數點後 2 位

equals 用法

當我們要比較兩個字符串是否相等時使用。

跟javascript不同的是當我們使用 str1 == str2時比較的是內存中儲存的首地址

String Str1 = new String("runoob");
String Str2 = Str1;
boolean retVal;

retVal = Str1.equals( Str2 );
System.out.println("返回值 = " + retVal );

Compareto 用法

返回参与比较的前后两个字符串的asc码的差值,如果两个字符串首字母不同,则该方法返回首字母的asc码的差值

 String a1 = "a";
 String a2 = "c";        
 System.out.println(a1.compareTo(a2));//结果为-2

如果两个字符串不一样长,可以参与比较的字符又完全一样,则返回两个字符串的长度差值

// 按字母顺序排列 (in alphabetical order):
if(firstString.compareTo(secondString) < 0) {

  System.out.println(firstString.toLowerCase()+" "+secondString.toLowerCase());
}

注意:数字类型不能用compareTo,nt跟int的比较不能用compareTo方法,直接用大于(>) 小于(<) 或者 等于(==) 不等于(!=)来比较即可

Character operations

注意此方法只能用在char

isLetter(c) true if alphabetic:
a-z or A-Z
isLetter('x') // true
isLetter('6') // false
isLetter('!') // false

toUpperCase(c) Uppercase version
toUpperCase('a')  // A
toUpperCase('A')  // A
toUpperCase('3')  // 3
isDigit(c) true if digit: 0-9.
isDigit('x') // false
isDigit('6') // true
toLowerCase(c) Lowercase version
toLowerCase('A')  // a
toLowerCase('a')  // a
toLowerCase('3')  // 3
isWhitespace(c) true if whitespace.
isWhitespace(' ')  // true
isWhitespace('\n') // true
isWhitespace('x')  // false

擷取字符串

String Str = new String("This is text");
 
System.out.print("返回值 :" );
System.out.println(Str.substring(4) );
 
System.out.print("返回值 :" );
System.out.println(Str.substring(4, 10) );

數字

 轉為整數

Integer.parseInt()

Java 中將浮點數舍入到小數點後 2 位

double random = Math.random();
 
        String roundOff = String.format("%.2f", random);
        System.out.println(roundOff);

 取的數字最後幾位

剛開始本來想直接使用substring 但是要知道substring只用於字符串,以下為更簡易的方式

 // 獲取倒數後兩個數字
int lastTowDigit = highwayNumber % 100;

判斷字符是否為數字

System.out.println(Character.isDigit(1)); // 返回false
System.out.println(Character.isDigit("1")); // 返回true

隨機數

 System.out.println("Math.random()=" + Math.random());// 结果是个double类型的值,区间为[0.0,1.0)
        int num = (int) (Math.random() * 3); // 注意不要写成(int)Math.random()*3,这个结果为0,因为先执行了强制转换
        System.out.println("num=" + num);

你可能感兴趣的:(java,开发语言)