2010-10-08 32 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