2017-04-05 8 views
-1

//ハリー、スー、メアリー、ブルース、ハリー、メアリー、スーのようにプリントアウトする必要があります //しかし、なぜそれが分からないのか分かりませんでしたか?すでに名前があなたがちょうどそう横の名前並べ替え私はアルファベット順に私の行を並べ替えない理由を理解する

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

のような分割方法を使用するか、外部の区切り文字を定義する必要がありますProcessNameのために渡された行にカンマ区切りになることを知っているので //

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

先生に会いに行く必要がありました –

答えて

1

を助けてください一方、代わりに内部

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

私は固定オリジナルを投稿しました。あなたはちょうど内側の代わりにあなたの上の区切り文字を宣言しなければならなかった –

1

は、それが仕事を得るために最小限の変更では、whileループの前にscn.useDelimiterコールを移動することです。

これは宿題に関する質問ですので、必ずしも正しい場所にないと思われるものがいくつかあることをご了承ください。しかし、私は彼らが最終結果に影響を与えるとは思わない。

+0

返済ありがとう –

関連する問題