2011-09-26 69 views
2

我試圖測試一個程序,如果用戶輸入一個空格將打印「空間」。 但是當我點擊空間時顯示nothings,然後輸入。我的目標是真正計算空間的數量,但我想我只是從這開始。幫助我的傢伙,感謝您的任何幫助 這裏是我的代碼 import java.util.Scanner;比較字符與單個空間java

public class The 
    { 
     public static void main(String args[])throws Exception 
     { 
      Scanner scanner = new Scanner(System.in); 
      String input; 
      System.out.println("Enter string input: "); 
      input = scanner.next(); 
      char[] charArray; 
      charArray = input.toCharArray(); 

      for(char c : charArray) 
      { 
        if(c == ' ') 
        { 
        System.out.println("space"); 
        } 
        else 
        { 
        System.out.println(" not space"); 
        } 
      } 
     } 
    } 

回答

1

Scanner默認情況下忽略空格。使用BufferedReader來讀取輸入。

+0

我忘了使用的BufferedReader,非常感謝你.. –

1

默認情況下,掃描程序將忽略所有包含新行,空格和製表符的空白。然而,你可以很容易地改變它是如何將您的輸入:

scanner.useDelimiter("\\n"); 

這會讓你的掃描儀只能在新線分割字符串,所以直到你按下輸入它會「讀」所有的空格字符了。查找分隔符here的更多自定義選項。

+0

感謝您的幫助.. –

0

公共類CountSpace {

public static void main(String[] args) throws IOException { 

    BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
    String word=null; 
    System.out.println("Enter string input: "); 
    word = br.readLine(); 
    String data[] ; 
    int k=0; 
    data=word.split(""); 
    for(int i=0;i<data.length;i++){ 
     if(data[i].equals(" ")) 
     k++; 
    } 
    if(k!=0)   
    System.out.println(k); 
    else 
     System.out.println("not have space"); 

} 

}