2010-10-08 20 views
1

的空格数我必须做一个分配如下:的Java:在循环中使用的charAt并确定输入

编写一个程序,确定输入行的空格数。在行中读入一个字符串。接下来在循环中使用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.*/ 

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

回答

2

两个与您的代码的问题:

  1. 移动System.out.printlnfor外块,所以它只能打印一次。
  2. 您的代码正在计算字符串中的字母数量,而不是空格数量。您可以通过使用Character.isSpaceChar(c)(仅限空格)或Character.isWhitespace(c)(任何空格字符,如空格或制表符)来判断一个字符是否为空格。
+0

好的感谢您的意见。我会放弃它。 – Bewithched 2010-10-08 17:38:05