如何测试Java中的输入字符串是否为空

时间:2016-09-23 15:31:27

标签: java string null

所以我创建了一些代码来检查用户输入的单词的第一个字母(存储在变量单词中)是辅音还是元音。如果它既不是输出说它既不是。但是,我使用nextLine()而不是next()来获取输入。我知道next()在输入除空格之外的有效字符之前不会接受输入,并且我知道如果只输入空格,则nextLine()将转到else语句。但是,在nextLine中,当用户只是输入并且没有输入任何字符,没有空格时,程序崩溃。我试着检查字符串是否等于null,然后将其打印出来" test"如果它被证明是真的,但是出于某种原因,每当我按下回车,我仍然会收到错误。以下是我的代码:

 import java.util.Scanner;
public class WordStart {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.printf("Please enter a word: ");
        String word = in.nextLine();
        String lowerWord = word.toLowerCase();
        String x = lowerWord.substring(0,1);
        String test = null;
        String empty = new String();


        boolean vowel = x.equals("a")||x.equals("e")||x.equals("i")||
                        x.equals("o")||x.equals("u");
        boolean conc = x.equals("b")||x.equals("c")||x.equals("d")||x.equals("f")||
                        x.equals("g")||x.equals("h")||x.equals("j")||x.equals("k")||
                        x.equals("l")||x.equals("m")||x.equals("n")||x.equals("p")||
                        x.equals("q")||x.equals("r")||x.equals("s")||x.equals("t")||
                        x.equals("v")||x.equals("w")||x.equals("x")||x.equals("y")||
                        x.equals("z");


        if(vowel){
            System.out.printf("%s starts with a vowel.\n", word);
        }
        else if(conc){
            System.out.printf("%s starts with a consonant.\n", word);
        }
        else if(word.equals("")){
            System.out.println("testEmpty");
        }
        else if(word.isEmpty()){
            System.out.println("testNull");
        }
        else{
            System.out.printf("%s starts with neither a vowel nor a consonant.\n", word);
        }

    }

}

基本上,我试图检查用户是否只是在没有输入任何内容的情况下按下输入并将其调出。什么方法,代码行可以帮助我做到这一点。我尝试使用word.equals(null),但IDE说它从来都不是真的。提前致谢。

我按Enter键时得到的错误代码如下

run:
Please enter a word: 
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
    at java.lang.String.substring(String.java:1963)
    at WordStart.main(WordStart.java:8)
C:\Users\Jordan\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)

3 个答案:

答案 0 :(得分:1)

我认为问题在于这一行:

String x = lowerWord.substring(0,1);

如果字符串为空(nextLine永远不会返回空字符串),则无法获取子字符串。你可能应该检查字符串是否> 0个字符。

if(x.length > 0)
  String x = lowerWord.substring(0,1);

答案 1 :(得分:1)

首先请注意word.equals("")word.isEmpty()检查相同的条件。所以没有必要同时使用它们。要检查String null是否使用if (word == null)。检查null和字符串的空白应该是你做的第一个。

其次,如果您跳过输入(获取空字符串""),则会得到IndexOutOfBoundsException,因为lowerWord.substring(0,1);没有机会找到该索引。

所以:

if (word != null && !word.isEmpty()) {
   // ...
}

答案 2 :(得分:0)

检查它是否为空

if(variable==null)

应该足够了