Question:
Sort the given series of English words by first letter and output the sorted results.
Such a method in StringcompareToIgnoreCase()
It ignores case and compares the order of two words in the dictionary. By using this method, this problem can be easily solved.
Related learning video recommendations: java video
The following is the demo code:
import java.util.Scanner; /* * 请对给出的一系列英文单词按首字母进行排序,并输出排序后的结果。 输入说明:数字N,表明单词数,接下来是N个英文单词; 输出说明:按字母序的排序结果。 输入样例:6 Apple banana Zebra Tuesday moon CAN 输出样例:Apple banana CAN moon Tuesday Zebra */ public class Sort { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("请输入单词的个数:"); int num = input.nextInt(); String[] strArr = new String[num]; System.out.println("请输入单词:"); for(int i = 0;i < strArr.length;i++) { strArr[i] = input.next(); }//将键盘输入的单词输入到String数组中 wordSort(strArr); } public static void wordSort(String[] strArr) { //比较单词字典顺序 用冒泡排序法比较 for(int i = strArr.length - 1;i > 0;i--) { for(int j = 0;j < i;j++) { if(strArr[j].compareToIgnoreCase(strArr[j + 1]) > 0) { String temp = strArr[j]; strArr[j] = strArr[j + 1]; strArr[j + 1] = temp; } } } for(String i : strArr) { System.out.println(i); } } }
There are many ways to solve this problem, not all of them here. Everyone introduces, welcome everyone to come to the PHP Chinese website to learn together.
For more related articles, please visit: Getting Started with Java
The above is the detailed content of How to sort input words by first letter in java. For more information, please follow other related articles on the PHP Chinese website!