编程:OJ系统Java语言编程技巧

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()){};

(待续)持续更新