使用Java检查用户的输入是否为空

时间:2017-01-22 15:13:04

标签: java java.util.scanner

我环顾四周,无法找到解决方案。我的代码应该从用户那里获取输入,并在输入为空时停止。代码起初很简单,但现在我觉得我已经过度复杂了很抱歉。

Scanner read = new Scanner(System.in);
System.out.println("Input words, enter blank to stop");
boolean working = true;
do {
    if(working == false)
    {
        break;
    }

    String a = read.next();

    if (a.equals("")) {
        working = false;
        System.out.println("no data");    
    } else {
        Container.addWord(a);
    }
} while (working == true);

感谢。

6 个答案:

答案 0 :(得分:2)

将next()更改为nextLine():

    Scanner read = new Scanner(System.in);
    System.out.println("Input words, enter blank to stop");
    boolean working = true;
    do {
        if (working == false) {
            break;
        }
        String a = read.nextLine();
        if (a.isEmpty()) {
            working = false;
            System.out.println("no data");

        } else {

            Container.addWord(a);
        }

    } while (working == true);

答案 1 :(得分:1)

您是否尝试过使用String#trim().isEmpty()

它还会将" "之类的字符串视为空。

do {
    String a = read.next();

    if (a.trim().isEmpty()) {
        working = false;
        System.out.println("no data");    
    } else {
        Container.addWord(a);
    }
} while (working);

答案 2 :(得分:1)

我认为您的代码可以替换为以下内容:

Scanner read = new Scanner(System.in);
System.out.println("Input words, enter blank to stop");
while(true) {    
    if (!read.hasNext()) {
        System.out.println("no data");
        break; 
    }
    String a = read.next();
    Container.addWord(a);
}

我还删除了working变量,并将其替换为break语句。

如果您将read.next()更改为read.nextLine(),请务必同时将read.hasNext()更新为read.hasNextLine()

答案 3 :(得分:1)

这是一个更优雅的版本

public static void main(String...args){
    Scanner read = new Scanner(System.in);
    String line = null;
    System.out.println("Enter text:");
    while(!(line=read.nextLine()).equals("")){
        System.out.println("Your text:"+line);
        System.out.println("Enter text or press enter to exit:");
    }

    System.out.println("Bye bye !!!");
}

答案 4 :(得分:0)

yourString.isEmpty() || yourString.equals("")

答案 5 :(得分:0)

你可以简化整个事情:

    Scanner read = new Scanner(System.in);
    System.out.println("Input words, enter blank to stop");
    boolean working = true;
    do {
      String keyEntered = read.nextLine();

      if (keyEntered.isEmpty()) {
        working = false;
        System.out.println("No data");
      } else {
        System.out.println("You entered: " + keyEntered);
      }
    } while (working);