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:
- Move the
System.out.println
to outside thefor
block, so that it only prints once. - 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) orCharacter.isWhitespace(c)
(any whitespace character, such as space or tab).
精彩评论