开发者

compare character with single space java

i'm trying to test a program that will print "space" if the user enters a single space. but nothings displayed when i hit space then enter. my aim was really to count the number of spaces but i guess i'll just start with this. help me guys, thanks for any help here's my code import java.util.Scanner;

    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("spa开发者_JAVA技巧ce");
                  }
                  else
                  {
                  System.out.println(" not space");
                  }
             }
         }
     }


Scanner ignores spaces by default. Use BufferedReader to read input.


By default, Scanner will ignore all whitespace, which includes new lines, spaces, and tabs. However, you can easily change how it divides your input:

scanner.useDelimiter("\\n");

This will make your Scanner only divide Strings at new line, so it will "read" all the space characters up until you press enter. Find more customization options for the delimiters here.


public class 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");

}

}

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜