简体   繁体   English

如何检查字符是否等于空格?

[英]How can I check if the character equal space?

I need to check if the array of character [i] equal space or not我需要检查字符数组 [i] 是否等于空格

Please look at the code:请看代码:

import java.util.Scanner;

public class Main {
public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.println("\tplease enter text");
    System.out.print("\t");
    String text = in.next();

    for(int i =0;i<text.length();i++)
    {
        if(text.charAt(i) == 'a') // case a
        {
            System.out.println("it is  > a");
        }
        else if(text.charAt(i) == ' ') // case space
        {
            System.out.println("it is a  > space");
        }
    }
    
    
}// main

} }

Whene (text.charAt(i) == ' ') TRUE It doesn't do the statement Whene (text.charAt(i) == ' ') TRUE 它不执行该语句

text.charAt(i) == ' ' will not be true since you use Scanner 's next method and thus your text variable will not contain a space. text.charAt(i) == ' '将不成立,因为您使用Scannernext方法,因此您的text变量将不包含空格。

By default a Scanner 's delimeter is whitespace, so your call of默认情况下, Scanner的分隔符是空格,因此您调用

String text = in.next();

will cause text to only contain data up until the first space of your input.将导致text仅包含数据,直到您输入的第一个空格。 You can verify this using a System.out.println(text) .您可以使用System.out.println(text)来验证这一点。

Use String text = in.nextLine();使用String text = in.nextLine(); instead.反而。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM