2017-04-05 27 views
-1

//输入哈利,苏,玛丽,布鲁斯应该打印出来像布鲁斯,哈利,玛丽,苏 //但我只得到它打印出来,它还没有被排序不确定为什么? //请帮助水平名称排序我无法弄清楚它为什么不选我行按字母顺序

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

的调用Collections.sort(名);在完成读取字符串的所有输入之后。在解析时排序它没有意义。把它放在你的时间之外,然后再打印名字。 –

+0

是的IM升技卡住必要去看看老师 –

回答

1

既然你已经知道的名字将是逗号传递给processName你应该只使用分割方法,像这样

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); 
    } 
} 

或外部定义分隔符行分隔的同时,而不是内部

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 
+0

嘿感谢RAZ_Muh_Taz大加赞赏 –

+0

你如此接近你的最初实现在i贴固定原件。您只需在上面声明分隔符,而不是在 –

1

看着它,最小的变化来得到它的工作将是while循环之前,移动电话scn.useDelimiter

由于这是一个家庭作业的问题,我会离开你的提示,有几个东西,一定不是在正确的地方。但我不认为他们影响最终结果。

+0

感谢您的反馈 –

相关问题