开发者

Java: Using charAt in a loop and determining the number of spaces in the input

I have to do the following for an assignment:

Write a program that determines the number of spaces in an input line. Read in the line into a string. Next use the charAt( ) method in a loop to access the characters one by one.

The code I have thus far:

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" + " "+ co开发者_StackOverflow中文版untCharacters + " " + "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.*/

How do I get it to choose each character? I am not sure the program I wrote is giving the solution for the 2nd part.


Two issues with your code:

  1. Move the System.out.println to outside the for block, so that it only prints once.
  2. Your code is counting the number of letters in the string, not the number of spaces. You can tell if a character is a space by using Character.isSpaceChar(c) (spaces only) or Character.isWhitespace(c) (any whitespace character, such as space or tab).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜