gpt4 book ai didi

Java:在循环中使用 charAt 并确定输入中的空格数

转载 作者:行者123 更新时间:2023-11-30 05:09:39 24 4
gpt4 key购买 nike

我必须为作业执行以下操作:

编写一个程序来确定输入行中的空格数。将行读入字符串。接下来在循环中使用 charAt( ) 方法来逐个访问字符。

我到目前为止的代码:

import javax.swing.*;

import java.lang.Character;

public class Assignment5_CHESHIRE {
public static void main(String[] args)
{

String Sentence=JOptionPane.showInputDialog("Please enter an word or words: ");
int countCharacters=0;

for (int i = 0; i< Sentence.length(); i++)
{
char c=Sentence.charAt(i);
if (Character.isLetter(c)) {
countCharacters++;
}

System.out.println("There are" + " "+ countCharacters + " " + "letters" +" " + "in the Words " + Sentence);
}

}

}
/*
Example of the output:
--------------------Configuration: Assignment5_CHESHIRE - JDK version 1.6.0_21 Assign5 - <Default>--------------------
There are 1 letters in the Words Kitty whiskers
There are 2 letters in the Words Kitty whiskers
There are 3 letters in the Words Kitty whiskers
There are 4 letters in the Words Kitty whiskers
There are 5 letters in the Words Kitty whiskers
There are 5 letters in the Words Kitty whiskers
There are 6 letters in the Words Kitty whiskers
There are 7 letters in the Words Kitty whiskers
There are 8 letters in the Words Kitty whiskers
There are 9 letters in the Words Kitty whiskers
There are 10 letters in the Words Kitty whiskers
There are 11 letters in the Words Kitty whiskers
There are 12 letters in the Words Kitty whiskers
There are 13 letters in the Words Kitty whiskers

Process completed.*/

如何让它选择每个角色?我不确定我编写的程序是否给出了第二部分的解决方案。

最佳答案

您的代码有两个问题:

  1. System.out.println 移至 for block 之外,以便它只打印一次。
  2. 您的代码正在计算字符串中的字母数,而不是空格数。您可以使用 Character.isSpaceChar(c)(仅限空格)或 Character.isWhitespace(c)(任何空白字符,例如空格)来判断字符是否为空格或选项卡)。

关于Java:在循环中使用 charAt 并确定输入中的空格数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3892872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com