///yuec2 yue chengpackage lab1;import java.util.Arrays;import java.util.Scanner;/**NameSorter class takes n number of names in the form of string inputs * from the user. It then asks user for which name to search for. * It sorts the names entered by the user, and then prints the * position of the search-name in the sorted list of the names, * if it is found. */public class NameSorter { Scanner input = new Scanner(System.in); /**getNameInputs takes an int parameter n and creates an array of size n. * It then asks user to Enter n names that get stored in the array. * It uses the helper method toTitleCase() to convert all names to Title case. * It returns the array filled with names entered by the user. */ String[] getNameInputs(int n) { //write your code here String[] names = new String[n]; for (int i = 0; i < n; i++) { names[i] = input.next(); } return names; } /**toTitleCase() takes one string argument as name and returns the string in title case. * If the name is null or the string is empty, it returns null. */ String toTitleCase(String name) { //write your code here if (name == null || name.length() == 0) return null; char c = name.charAt(0); char cap = Character.toUpperCase(c); String sub = name.substring(1); StringBuilder sb = new StringBuilder(); sb.append(cap); for (int i = 0; i < sub.length(); i++) { sb.append(Character.toLowerCase(sub.charAt(i))); } return sb.toString(); } /**sortAndSearch() takes two arguments. The first is an array of strings and the second * is a searchString. The method first sorts the array in increasing alphabetical order, * and prints it in that order. * It then searches for the searchString in a case-insensitive way. If the searchString is found, * it returns the position of the searchString according to the sorted list. * If it is not found, then it returns -1. */ int sortAndsearch(String[] strings, String searchString) { int pos = -1; if (strings == null || strings.length == 0 || searchString == null) return pos; //write your code here Arrays.sort(strings); for (int i = 0; i < strings.length; i++) { if (strings[i].equalsIgnoreCase(searchString)) return i; } return pos; } /**DO NOT CHANGE THIS METHOD */ public static void main(String[] args) { NameSorter ns = new NameSorter(); System.out.println("*** How many names to store? ***"); int n = ns.input.nextInt(); if (n > 0) { String[] names = ns.getNameInputs(n); System.out.println("*** Enter the name to search ***"); String name = ns.input.next(); int position = ns.sortAndsearch(names, name); if (position >=0 ) System.out.println(name + " found at position " + (position+1)); else System.out.println("Sorry! " + name + " not found!"); } else System.out.println("Good Bye!"); }}
读懂题、先写cc equalsIgnoreCase等给的函数要用
Arrays.sort(strings);自动按首字母排序
注意names[i] = input.next();和nextline()的区别
String[] getNameInputs(int n) { //write your code here String[] names = new String[n]; for (int i = 0; i < n; i++) { names[i] = input.next(); } return names; }