如何在 JAVA 中输入空字符串

How to input an Empty string in JAVA

我的程序应该检查 s 是否为空字符串,如果找到,它应该打印 "Empty string" 并提示输入新的内容。但是我的第一个 运行 没有要求 s,打印 "Empty String",然后它 运行s 完美!

Scanner input = new Scanner(System.in);
int t = input.nextInt();
while (t > 0) {
    String s;
    s = input.nextLine();
    if (s.isEmpty()) {
        System.out.println("Empty string");
        s = input.nextLine();
    } 
}

如何避免第一个 "Empty String"?

PS- 我试过了 -

s = input.next();

这解决了问题,但现在它不允许我在程序中输入空字符串!

PPS- 检查一下:

import java.util.*;
import java.lang.*;
import java.io.*;

class ComparePlayers {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int t = input.nextInt();
        while (t > 0) {
            String s;
            s = input.nextLine();
            if (s.isEmpty()) {
                System.out.println("Empty String");
                s = input.nextLine();
            }
            else {
                System.out.println("Not Empty");
            }
            t--;
        }
    }
}

您可以看到有 3 个 i/ps,其中一个 o/ps 被空字符串占用。

这是因为Scanner.nextInt()方法不读取'\n'(换行)按'生成的字符Enter' 在终端输入中输入数字后。一个简单的解决方法是使用 input.nextLine() 读取 '\n' 字符,并在使用 Scanner.nextX() 方法(例如 nextInt()、nextDouble( ), 等等)

因此您的代码更改为:

Scanner input = new Scanner(System.in);
int t = input.nextInt(); 
input.nextLine(); // read and ignore extra \n character

while (t > 0) {
    String s;
    s = input.nextLine();
    if (s.isEmpty()) {
        System.out.println("Empty string");
        s = input.nextLine();
    } 
}

它这样做是因为 input.nextInt(); 没有捕获换行符。您可以像其他建议的那样添加 input.nextLine();

Scanner input = new Scanner(System.in);
int t = Integer.parseInt(input.nextLine());
while (t > 0) {
    String s = input.nextLine();
    if (s.isEmpty()) {
        System.out.println("Empty string");
        s = input.nextLine();
    }
}