java - 如何排序忽略大写的数组?

标签 java arrays sorting

我使用 sort() 按字母顺序对我的数组进行排序,但它是从 A-Z 到 a-z 排序的。我尝试预先将每个单词大写,但它不起作用,除非它被打印出来,这应该在排序之后发生。目前,使用此代码,它会列出大写字母的学生,但如果输入的是小写字母,则会按小写字母排序。在将输入分配给数组后立即将 capitalize() 放在初始 for 循环中是行不通的。任何解决方案?

import java.util.Scanner;
import java.util.Arrays;

public class Pupils {
public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    boolean loop = true;
    int names = 0;

    String[] ay = new String[1000];

    for(int i = 0; loop == true; i++) {
            System.out.println("Enter name: ");
            ay[i] = scan.nextLine();
            names++;
            if (ay[i].equals("0")) {
                loop = false;
                ay[i] = " ";
        }
    }

    String[] aay = new String[names - 1];

    for(int i = 0; i < aay.length; i++) {
        aay[i] = ay[i];
    }

    if (names == 1) {
        System.out.print("There are no people in our class.");
    } else if (names == 2) {
        System.out.print("The person in our class is ");
    } else {
        System.out.print("The people in our class are ");
}
    Arrays.sort(aay);
    for(int i = 0; i < names - 1; i++) {
        if(i == names - 2) {
            System.out.print(capitalize(aay[i]) + ".");
        } else if (i == names - 3) {
            System.out.print(capitalize(aay[i]) + " and ");
        } else {
            System.out.print(capitalize(aay[i]) + ", ");
        }
    }

}
public static String capitalize(String line)
{
  return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}

}

最佳答案

使用 Arrays.sort() with a Comparator 怎么样? ?请注意,有一个 suitable comparator defined in String ,所以:

Arrays.sort(aay, String.CASE_INSENSITIVE_ORDER);

应该完成这项工作。

关于java - 如何排序忽略大写的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28285528/

相关文章:

javascript - 是否所有修改方法都调用数组代理的设置陷阱

c - C语言中的简单数组

使用 Thrust CUDA 对对象进行排序

ios - 通过按钮对表格 View 中的单元格进行排序

java - 使用计时器进行 ScheduleAtFixedRate

java - 如果我使用 struts 或 servlet 或 spring,则 main 方法将在我的 Web 应用程序中创建

java - 如何检测 Jscrollpane 中的滚动条被拖动/单击?

java - Spring MVC - 使用 @ExceptionHandler 处理异常不会呈现新 View

使用递归的 Java 多米诺骨牌平铺 : second if block gets called with already updated values

.net - DataGridView 排序和例如.NET 中的 BindingList<T>