JAVA刷题必会代码片段

232 阅读1分钟
  • 接收控制台输入单个数值
Scanner in = new Scanner(System.in);
int n = in.nextInt();
double x = in.nextDouble();
in.nextLine();//这里单独写这一句是为了清除控制台中的换行符,防止之后接收一整行数据接收到空
  • 接收一整行输入
String s = in.nextLine();
  • 接收输入并按照空格分割为字符串数组
String[] s = in.nextLine().split(" ");
  • 输出一个内容不换行
System.out.print("hello world");
  • 保留一定小数个数输出数值
System.out.printf("%.1f",0.55);
  • int 转long
long num = Long.parseLong(x);
  • 绝对数
Math.abs(x);
  • 四舍五入
Math.round(x);
  • 向上取整
double ceilValue = Math.ceil(x);
  • 向下取整
double floorValue = Math.floor(x);
  • 开方计算
double sqrtValue = Math.sqrt(x);
  • 次运算
double powerValue = Math.pow(x, 2);
  • 数组的创建
int[] intArray = new int[x];//x为容量
  • 二维数组的创建
int[][] intArray2D = new int[x][y];
  • 获取二维数组的子项数组
//x为二维数组
int[] y = x[0];
  • 数值类型数组的升序排序
Arrays.sort(intArray);
  • 数组是否包含某个值
boolean ifContain =  Arrays.asList(dict).contains(x);
  • 数值类型数组的降序排序
Arrays.sort(x);
int[] y = new int[x.length];
for (int i = 0; i < x.length; i++) {
    y[i] = x[x.length - 1 - i];
}
  • 数值类型数组的自定义排序
Arrays.sort(x, new Comparator<Integer>() {
    @Override
    public int compare(Integer a, Integer b) {
        return a - b; // 从小到大排序
    }
});

  • 字符串转int类型
int intValue = Integer.parseInt(str);
  • 字符串是否相同比较
boolean isSame = x.equals(y);
  • 字符串的截取
String x = y.substring(2, 4);// [2,4)
  • 去掉行首和行尾的空格
String trimmed = input.trim();
  • 把相邻单词间的多个空格换成 1 个空格
x = x.replaceAll("\\s+", " "); 
  • 把标点符号前面的空格删掉
x = x.replaceAll("\\s+(?=\\p{Punct})", "");
  • list的创建
List<Integer> x = new ArrayList<>();
  • list子项增加
x.add(1);
  • map的创建
Map<String, Integer> x = new HashMap<>();
  • map的增加子项
x.put("a", 1);
  • map结构通过key获取值,若获取不到则返回设定值
int value = x.getOrDefault("d", 0);
  • map的遍历(默认无序存储,遍历也无序)
for (Map.Entry<String, Integer> entry : x.entrySet()) {
    String key = entry.getKey();
    int value = entry.getValue();
    System.out.println(key + ":" + value);
}
  • map的有序存储及有序遍历
Map<String, Integer> x = new HashMap<>();
x.put("a", 1);
...
Map<Integer,Integer> sort = new TreeMap<>(x);