Когда я попытался проанализировать каждое слово строки отдельно, первое слово было сделано хорошо, но я потерпел неудачу для остальных. Помогите мне исправить этот код 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
Рабочий код как needed-->
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");
}} }
Проблема заключалась в том, что вы указали приращенные значения в неправильном месте и, следовательно, неправильно работали с ними. Я немного изменил код, посмотрю, поможет ли он вам:
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
Вывод:
Слово [xyz] имеет [3] символы и содержит [1] x и [2] не-x.
Слово [xyxzghz] имеет [7] символов и содержит [2] x и [5] не-x.
Слово [zyxzz] имеет [5] символов и содержит [1] x и [4] не-x.
Примечание. Регулярное выражение, используемое для разделения на символы, которые я использовал, было "(?!^)"
Вместо ""
потому что последний создает ненужный пустой символ как 0-й элемент в массиве (попробуйте его). Разделение на символы или односимвольные массивы String можно выполнять по-разному, но это всего лишь пример.
Убедитесь, что вы сбросили счет 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");
}
count1
переменную count1
& chars_not_x
внутри цикла или count1
инициализируйте count1
и chars_not_x
с 0 на каждой итерации.