得到正确的单词形式数组

时间:2013-01-14 21:28:54

标签: java arrays for-loop while-loop format

我在从阵列中正确打印时遇到问题。

在IF(A)中, 这应该以这种方式格式化所有输入字母。

等等等

但是,以下只会格式化我写的最后一个单词。我只是猜测为什么,而且不知道如何解决它。

该部分标有:**“

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

1 个答案:

答案 0 :(得分: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)+ " ");
    }
  }
}

如果你有e个单词(例如"cat""dog""end"),则输出为"c a t d o g"。如果您还想要“e n d”,请更改

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

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

我还要说,既然您正在使用数组,那么用户可以提前结束(保留其余索引null),您应该考虑使用ArrayList <String>代替。