Java find array elements of specified type

Title description

Enter an integer n, and then enter n strings, and save the n strings in an array. Find the smallest string in the above array elements in lexicographic order (you can directly use the compareTo method to determine the size), and output the subscript of the string in the array and the value of the string itself in a separate line, separated by spaces . If there are multiple elements that meet the requirements, just output the relevant content of the element with the largest subscript.

Input sample

5
beautiful am peace holy am

Sample output

4 am

code

import java.util.Scanner;
public class Main{
    
    

    public static void main(String[] args) {
    
      // 主方法
        int min_index = 0;   // 最小的字符串索引

        Scanner n_scanner = new Scanner(System.in);  // 输入 beautiful am peace holy am
        int n = n_scanner.nextInt();  // 输入一个整数n

        Scanner str_scanner = new Scanner(System.in);
        String[] str_arr = new String[n];  // 创建字符串数组对象

        for(int i = 0; i < n; i++) {
    
    
            str_arr[i] = str_scanner.next();  // 对字符串数组赋值
        }

        for (int i = 0; i < str_arr.length - 1; i++) {
    
    
            if(str_arr[0].compareTo(str_arr[i + 1]) >= 0){
    
      // 数组元素中按字典顺序比较最小的字符串
                str_arr[0] = str_arr[i + 1];     // 找到最小字符串赋值给字串数组的第一个元素
                min_index = i + 1;          //   找到最小字符串的下标赋值给 min_index
            }
        }
        System.out.println(min_index + " " + str_arr[0]);  // 输出下标和最大的那个元素的相关内容
    }
}

Note: The
compareTo()method is used to compare the two methods:

  • The string is compared with the object.
  • Compare two strings lexicographically.

The return value is an integer. It first compares the size of the corresponding characters (in ASCII code order). If the first character is not equal to the first character of the parameter, the comparison ends and the difference between them is returned. If the first If the character is equal to the first character of the parameter, the second character is compared with the second character of the parameter, and so on, until the compared character or the compared character ends.

例如
String str1; String str2;
str1.compareTo(str2);

  • If str1 is equal to str2, the return value is 0;
  • If str1 is less than str2, return a value less than 0;
  • If str1 is greater than str2, a value greater than 0 is returned.

Guess you like

Origin blog.csdn.net/qq_44989881/article/details/112366021