java - Java Array嵌套for循环,不清除第二个for回到第一个
问题描述
下面代码中的 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();
}
}
我一直在寻找类似的东西,但只能找到其他语言。感谢所有的帮助。
解决方案
在第一组嵌套循环中,您基本上每次都检查每个单词的相同字符。您应该使用count作为 charAt 方法的参数,而不是i中的任何索引;此外,您应该只在count等于单词的长度减一时打印出单词。
这里是:
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 == array[i].length()-1) {
System.out.println(array[i]);
break;
}
}
}
}
}
我还重写了第二组嵌套循环,它应该自我解释:
else if(answer.equals("One"))
{
for (int i = 0; i < array.length;i++) {
int count = 0;
for (int j = 0; j < array[i].length(); j++) {
if (Character.isSpaceChar(array[i].charAt(j)))
count++;
}
if (count == 1) {
System.out.println(array[i]);
}
}
}
编辑:我忘了提到我添加了你忘记的 break 语句。它确保当您到达字符串中的最后一个字符时退出 for 循环。如果没有此语句,您的应用程序会因为 IndexOutOfBoundsException 而在每次到达字符串末尾时崩溃。
推荐阅读
- android - 除了在警报管理器中打印之外如何做其他事情 [Flutter]
- css - 有没有办法在布局中继承 Bootstrap 类?
- spacy - 将 spaCy int 属性映射到字符串(unicode)属性
- sql - SQL查询从每个月的最后一周获取4年的记录
- django - 如何在 django 的多客户端应用程序中构建基于角色的权限访问?
- java - 如何在 Tomcat 中使一个类对 Spring 可用?
- algorithm - 部分洪水填充
- r - 在 data.table 中按行获取总和
- node.js - Socket.io 命名空间和房间:无法在带有令牌的特定 url 上接收事件
- javascript - React-native:如何根据在前一个屏幕上选择的数字呈现输入并能够存储输入