gpt4 book ai didi

java - 分别分析字符串的每个单词

转载 作者:行者123 更新时间:2023-11-29 07:02:27 25 4
gpt4 key购买 nike

当我试图分别分析一个字符串的每个单词时,第一个单词做得很好,但其余的我都失败了。帮助我更正此 JAVA 代码以获得正确的输出:

public class Test {

public static void main(String[] args) {


int count1=0;
int chars_not_x=0 ;

String str = "xyz xyxzghz zyxzz";
String[] words = str.split("\\s");

for(int m=0; m<words.length; m++){

System.out.println(words[m]);

System.out.println("Total characters in the word: "+words[m].length());
for(int n=0; n<words[m].length(); n++){
if(words[m].charAt(n)=='x'){count1++;}}

System.out.println("Number of x :"+count1);
chars_not_x= words[m].length()- count1;
System.out.println("Chars other than x: "+chars_not_x);

System.out.println("\n");


}} }

代码的输出是"

xyz
Total characters in the word: 3
Number of x :1
Chars other than x: 2


xyxzghz
Total characters in the word: 7
Number of x :3
Chars other than x: 4


zyxzz
Total characters in the word: 5
Number of x :4
Chars other than x: 1

所需的输出:

xyz
Total characters in the word: 3
Number of x :1
Chars other than x: 2


xyxzghz
Total characters in the word: 7
Number of x :2
Chars other than x: 5


zyxzz
Total characters in the word: 5
Number of x :1
Chars other than x: 4

最佳答案

根据需要工作代码-->

public class Test {
public static void main(String[] args) {

int count1=0;
int chars_not_x=0 ;

String str = "xyz xyxzghz zyxzz";
String[] words = str.split("\\s");

for(int m=0; m<words.length; m++){

count1 = 0; // Add this

System.out.println(words[m]);

System.out.println("Total characters in the word: "+words[m].length());
for(int n=0; n<words[m].length(); n++){
if(words[m].charAt(n)=='x'){count1++;}}

System.out.println("Number of x :"+count1);
chars_not_x= words[m].length()- count1;
System.out.println("Chars other than x: "+chars_not_x);
System.out.println("\n");


}} }

关于java - 分别分析字符串的每个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23927618/

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