当我试图分别分析字符串的每个单词时,第一个单词做得很好,但其余的都没有成功。帮我纠正这个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");
}} }
代码的输出是&#34;
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
答案 0 :(得分:2)
根据需要使用工作代码 - &gt;
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");
}} }
答案 1 :(得分:2)
问题是您在错误的位置声明了递增的值,因此错误地使用了它们。我已经改变了你的代码,看看它是否对你有帮助:
public static void main(String[] args) {
String str = "xyz xyxzghz zyxzz";
String[] words = str.split(" ");
for (String word : words) {
int xFound = 0;
int nonXFound = 0;
String[] chars = word.split("(?!^)");
for (String current : chars) {
if ("x".equals(current)) {
xFound++;
} else {
nonXFound++;
}
}
System.out.println("Word [" + word + "] has [" + chars.length + "] characters, and contains [" + xFound + "] x and [" + nonXFound + "] non-x.");
}
}
x
输出:
Word [xyz]有[3]个字符,包含[1] x和[2] non-x。
Word [xyxzghz]有[7]个字符,包含[2] x和[5] non-x。
Word [zyxzz]有[5]个字符,包含[1] x和[4] non-x。
注意:用于拆分我使用的字符的正则表达式是"(?!^)"
而不是""
,因为后者生成一个不需要的空白字符作为数组中的第0个元素(试试看)。分割为字符或单字符字符串数组可以用不同的方式完成,这只是一个例子。
答案 2 :(得分:2)
确保重置每个单词的x计数:
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++){
count1 =0; //**missing**
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");
}
答案 3 :(得分:0)
声明count1
&amp;循环中的chars_not_x
变量,或者在每次迭代时将count1
和chars_not_x
重新初始化为0。