英文:
Java String Array, count number of spaces " "
问题
以下是翻译好的代码部分:
if (answer.equals("No")) {
for (int i = 0; i < array.length; i++) {
int count = 0;
if (array[i] != null) {
for (int j = 0; j < array[i].length(); j++) {
if (array[i].charAt(j) == ' ') {
count++;
}
}
if (count == 0) {
System.out.println(array[i]);
}
}
}
}
请注意,我在代码中做了一些修改,以正确计算字符串中的空格数并显示满足条件的字符串。
英文:
I am requesting a string from the user. After the user enters their strings a prompt asks if they want to see strings with no, one or more spaces in their strings, then displays the strings.
I am running into issues with counting the spaces in the string. The code provided only counts 1 if there is more than one space in the string. Whole code:
import java.util.*;
import java.util.Scanner;
public class CountSpacesInStrings {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String[] array = new String[20];
System.out.println("Please enter anything..., or type QUIT to quit.");
for (int i = 0; i < array.length; i++) {
array[i] = s.nextLine();
boolean result = Arrays.stream(array).anyMatch("QUIT"::equals);
if(result)
{
break;
}
}
String str = null;
int len = -1;
System.out.println("Would you like to display strings with No Spaces, One Space or More? Type No, One, More to see the results: ");
String answer = s.nextLine();
if(answer.equals("No")){
for (int i = 0; i < array.length;i++) {
int count = 0;
if (array[i] != null) {
if (array[i].charAt(i) != ' ') {
count++;
System.out.println(count);
}
}
}
}
else if(answer.equals("One"))
{
for (int i = 0; i < array.length;i++) {
int count = 0;
if (array[i] != null) {
if (array[i].charAt(i) != ' ') {
count++;
System.out.println(count);
}
//System.out.print(array[i] + " ");
}
}
}
else
System.out.println("No values to show");
System.out.println();
}
}
The section I'm looking at is:
if(answer.equals("No")){
for (int i = 0; i < array.length;i++) {
int count = 0;
if (array[i] != null) {
if (array[i].charAt(i) != ' ') {
count++;
System.out.println(count);
}
}
}
答案1
得分: 2
根据 @Pshemo 的评论:您需要添加一个嵌套的 for 循环。第二个 for 循环必须迭代遍历 array[i]
的内容(构成一个句子),并计算该句子中 ' '
字符的数量。
英文:
Based on the comment of @Pshemo: You would need to add a nested for loop. The second for loop has to iterate through the contents of array[i]
(which makes one sentence) and count the number of ' '
characters in that sentence.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论