Java重写compare方法实现数组降序排列

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        int index = scanner.nextInt();
        String[] s = str.split(" ");
        List<String> strings = Arrays.asList(s);
        Collections.sort(strings, new Comparator<String>() {
            //重写排序方法
            @Override
            public int compare(String o1, String o2) {
                int one = Integer.parseInt(o1);
                int two = Integer.parseInt(o2);
                if (one > two) {
                    return -1;
                } else if (one < two) {
                    return 1;
                } else {
                    return 0;
                }
            }
        });
        System.out.println(strings.get(index - 1));
    }
}

Java字符串反转

  • 方法一:使用StringBuilder
import java.util.Scanner;

public class StrReversal {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        System.out.println(new StringBuilder(str).reverse());
    }
}
  • 方法二:使用循环
import java.util.Scanner;

public class StrReversal {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        char[] chars = str.toCharArray();
        String reverse = "";
        for (int i = chars.length - 1;i>=0;i--){
            reverse += chars[i];
        }
        System.out.println(reverse);
    }
}
  • 方法三:考虑到String不可变,使用StringBuilder
import java.util.Scanner;

public class StrReversal {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        char[] chars = str.toCharArray();
        StringBuilder reverse = new StringBuilder();
        for (int i = chars.length - 1;i>=0;i--){
            reverse.append(chars[i]);
        }
        System.out.println(reverse);
    }
}