//进入Harry,Sue,Mary,Bruce应该像Bruce,Harry,Mary,Sue一样打印出来 //但是我只是把它打印出来了它还没有排序不确定为什么? //请帮忙
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
/**
* Exercise 31
* Horizontal Name Sort
* @author (Luke Dolamore)
* @version (5/04/17)
*/
public class Exercise31 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Input (end with #)");
String input = kb.nextLine();
while ( ! input.equals("#") ) {
processName(input);
input = kb.nextLine();
}
} //main
public static void processName (String line) {
Scanner scn = new Scanner(line);
ArrayList<String> name = new ArrayList<String>();
while ( scn.hasNext() ) {
line = scn.next();
scn.useDelimiter(",");
name.add(line);
Collections.sort(name);
}
for ( String nam : name ) {
System.out.println(nam);
}
}
} // class Exercise31
答案 0 :(得分:1)
由于您已经知道名称将在传递给processName的行中以逗号分隔,因此您应该只使用split方法
public static void processName (String line) {
ArrayList<String> name = new ArrayList<String>();
//splits the string around commas
String[] inputs = line.split(",");
//now take all the names/values that were seperated by the comma and add them to your list
for(int i = 0; i < inputs.length; i++)
{
name.add(inputs[i]);
}
//sort the list once
Collections.sort(name);
//output the names/values in sorted order
for ( String nam : name ) {
System.out.println(nam);
}
}
或者在while之外定义分隔符而不是在
之内public static void processName (String line) {
Scanner scn = new Scanner(line);
scn.useDelimiter(","); //declare it here
ArrayList<String> name = new ArrayList<String>();
while ( scn.hasNext() ) {
line = scn.next();
name.add(line);
}
Collections.sort(name);
for ( String nam : name ) {
System.out.println(nam);
}
}
示例运行1
Input (end with #)
bruce,harry,mary,sue
bruce
harry
mary
sue
#
示例运行2
Input (end with #)
z,x,y,r,g,q,a,b,c
a
b
c
g
q
r
x
y
z
答案 1 :(得分:1)
观察它,让它发挥作用的最小变化是在while循环之前移动BRK
调用。
由于这是一个家庭作业问题,我会告诉你,还有一些东西不一定在正确的地方。但是,我认为它们不会影响最终结果。