【发布时间】:2020-10-19 21:20:31
【问题描述】:
下面代码中的 for 循环首先遍历用户条目,然后检查字符串中空格“”的数量。在检查它们之后,会询问他们是否要显示没有空格、一个或多个空格的字符串。我不认为循环使它超过了 for 循环的第一个实例,因为第二个应该在 count 变量上寻找 0 值。下面是嵌套的 for 循环:
if(answer.equals("No")){
for (int i = 0; i < array.length;i++) {
if (array[i] != null) {
for (int count = 0; array[i].charAt(i) != ' ';count++) {
if(count == 0)
System.out.println(array[i]+" ");
}
}
}
}
主要参考代码:
import java.util.*;
import java.util.Scanner;
public class StringsWithSpaces {
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++) {
if (array[i] != null) {
for (int count = 0; array[i].charAt(i) != ' ';count++) {
if(count == 0)
System.out.println(array[i]+" ");
}
}
}
}
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();
}
}
我一直在寻找类似的东西,但只能找到其他语言。感谢大家的帮助。
【问题讨论】: