OJ系統Java語言編程技巧
常見題型:
最常見題型還是依賴於數組和字符串,需要熟練的操作,而java針對數組還有字符串都提供了大量的方法。可以簡化編程,同時也是對編程語言的一種掌握。下面羅列一些自己經常遇到很好用的一些技巧。
1、計算字符串數組最后一個單詞的長度:s[s.length - 1].length();
2、字符的大小寫裝換:
- 使用java字符串方法轉換,轉為大寫:s.toUpperCase(); 轉為小寫:s.toLowerCase();
- 使用字符ASCII碼轉換:大寫轉為小寫('char' + 32);小寫變為大寫('CHAR' - 32);
3、數據類型間的轉換:
- String 轉換為 char:s.charAt(index);
- char 轉換為 String:String.valueOf(char);
- String 轉換為 int:Integer.parseInt(s);//返回數值 。Integer.valueOf(s);// 返回對象 。Integer.valueOf(s).intValue(); // 返回數值 。
- int 轉換為 String:String.valueOf(i);//一個對象 。 s = i+""; //(拼接)兩個對象。
- char 轉換為 int:強轉 (int)('char'-48); // 先轉字符串再轉整型
- int 轉換為 char:強轉 (char)(i + 48);
注:Integer.parseInt(s,radix);方法可以根據進制轉換
4、ASCII碼的大致概念:使用了8位2進制數表示了128個字符,記住常用的:(48~57)為0~9的阿拉伯數字;(65~90)為26個大寫英文字母;(97~122)號為26個小寫英文字母;記住大寫和小寫字母的ASCII碼相差為32.
5、數值計算相關
- Math.sqrt(n):平方根;//求立方根Math.cbrt();求平方和Math.hypot();
- Math.pow(n,x):求n的x次方;
- Math.log():取自然對數,底數為e;
- Math.exp(x):取指數,e的x次方;
- Math.random():取隨機數(0~1之內,所以經常需要乘一個范圍域);
- Math.ceil(double a):向上取整;
- Math.floor(double a):向下取整;
- Math.round(double a):四舍五入取整;
6、保留結果位數
- 簡單輸出:System.out.println(String.format("%.2f",s));
- 構造格式對象:DecimalFormat df = new DecimalFormat("#.00"); System.out.println(df.format(number));
7、字符串的一些操作
- 字符串分割:str.substring(index); // str.split("");
- 字符串替換: str.replace();
- 字符串匹配:str.matches(regex);
- 字符串反轉:new StringBuffer(str).reverse();
8、Map操作
- 添加元素:map.put(key,value);
- 獲取元素:map.get(key); // key對應的value值
- 移除元素:map.remove(key); // 移除key對應的鍵值對
- 判斷是否包含key:map.containsKey(key); // boolean函數
- 判斷是否為空:map.isEmpty(); // true or false;
- Map遍歷:遍歷鍵值:for(Integer key : map.keySet()){}; 遍歷實體:for(Map.Entry<Integer, Integer> entry : map.entrySet()){};
(待續)持續更新