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

Java:在循环中使用charAt并确定输入中的空格数,java,Java,我必须完成以下任务: 编写一个程序,确定输入行中的空格数。把这行读入一个字符串。接下来在循环中使用charAt()方法逐个访问字符 迄今为止,我所掌握的守则: import javax.swing.*; import java.lang.Character; public class Assignment5_CHESHIRE { public static void main(String[] args) { String Sentence=JOptionPane.showInput

我必须完成以下任务:

编写一个程序,确定输入行中的空格数。把这行读入一个字符串。接下来在循环中使用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.*/
import javax.swing.*;
导入java.lang.Character;
公务舱分配5_CHESHIRE{
公共静态void main(字符串[]args)
{
字符串句子=JOptionPane.showInputDialog(“请输入一个或多个单词:”);
int countCharacters=0;
for(int i=0;i<句子长度();i++)
{
char c=句子charAt(i);
if(字符(c)){
计数字符++;
}
System.out.println(“单词“+句子”中有“+”+个字符++”个字母“+”);
}
}
}
/*
输出示例:
--------------------配置:Assignment5_CHESHIRE-JDK版本1.6.0_21 Assign5---------------------
单词Kitty whiskers中有1个字母
单词Kitty whiskers中有两个字母
Kitty whiskers这个词有三个字母
单词Kitty whiskers中有4个字母
Kitty whiskers这个词有5个字母
Kitty whiskers这个词有5个字母
Kitty whiskers这个词有6个字母
Kitty whiskers这个词有7个字母
Kitty whiskers这个词有8个字母
Kitty whiskers这个词有9个字母
Kitty whiskers这个词有10个字母
Kitty whiskers这个词有11个字母
Kitty whiskers这个词有12个字母
Kitty whiskers这个词有13个字母
进程已完成*/

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

您的代码有两个问题:

  • System.out.println
    移动到
    for
    块的外部,使其只打印一次
  • 您的代码正在计算字符串中的字母数,而不是空格数。您可以使用
    character.isSpaceChar(c)
    (仅限空格)或
    character.isWhitespace(c)
    (任何空格字符,如空格或制表符)来判断字符是否为空格

  • 好的,谢谢你的意见。我要试一试。