gpt4 book ai didi

java - 正确获取数组中的单词

转载 作者:行者123 更新时间:2023-12-02 00:03:45 25 4
gpt4 key购买 nike

我在从数组正确打印时遇到问题。

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

最佳答案

据我所知,您并未迭代所有索引

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" 。如果您还想拥有“en d”,请更改

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

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

我还要说,由于您使用的是数组,用户可能会提前结束(保留其余索引 null ,您应该考虑使用 ArrayList <String> 代替。

关于java - 正确获取数组中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14327024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com