2013-01-14 26 views
0

我遇到了從數組中正確打印的問題。獲取正確的單詞表格陣列

如果(A), 這應該以這種方式格式化所有的輸入字母。

℃的噸dö克等等等等

但是,以下只格式化的最後一個字寫我。我只是在猜測爲什麼,而不知道如何解決它。

那部分標有:**」

String type; 
String word; 
String words[]=new String[100]; 
int i=0; 

String k="end"; 
System.out.println("Type word: "); 
word=sc.next(); 

while(wyraz.compareToIgnoreCase(k)!=0){  
    words[i]=wyraz; 
    i=i+1; 
    word=sc.next(); 
} 
words[i]=k; 

System.out.println("Choose type A,B,C:"); 
type=sc.next(); 



**if(type.equals("A")){ 
    int length=word.length(); 

    for(int z=0;z<length;z++){ 
    System.out.print(words[z]=""+word.charAt(z)); 
    System.out.print(" "); 
}** 


if(type.equals("B")){ 
    int length=i+1; 

    for(int x=0;x<length;x++){ 
     System.out.print(words[x]); 
     System.out.println(); 
    } 
} 

if(type.equals("C")){ 

    int length=i+1; 
    int j; 

    for(i=0; i<length; i++) { 
     for(j=0; j<i; j++) { 
      System.out.print(" "); 
      System.out.print(words[j]); 
      System.out.println(); 
     } 
    } 
} 

回答

3

從我可以告訴,你是不是通過所有指標迭代

if(type.equals("A")){ 
    //iterate through all words except for "end" 
    for (int x = 0; x < i; x++){ 
    //iterate through specific word's characters 
    for(int z=0;z<words[x].length();z++){ 
     //actually print 
     System.out.print(words[x].charAt(z)+ " "); 
    } 
    } 
} 

這應該,如果你擁有電子的話(如"cat""dog""end"),輸出"c a t d o g"。如果你想也有 「結束」,改變

for (int x = 0; x < i; x++){ 

for (int x = 0; x <= i; x++){ 

我也會說,因爲你正在使用的陣列,用戶可以過早結束(在離開索引null的其餘部分,你應該考慮使用ArrayList <String>代替。

+0

謝謝!很多:)現在我明白了,問題在哪裏。 – Fokuz