How to input an Empty string in JAVA

newbie100 :

My program should check if s is an empty string and if found so, it should print "Empty string" and prompt for new input. But my every first run without asking for s, prints "Empty String", afterward it runs perfectly!

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();
    } 
}

How can I avoid the first "Empty String"?

PS- I tried -

s = input.next();

This solves the problem but now it won't let me input an Empty String into the program!

PPS- Check this out:

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--;
        }
    }
}

You can see there are 3 i/ps while one of the o/ps is taken up by the Empty String.

Meet Sinojia :

This is because Scanner.nextInt() method does not read '\n' (new line) character generated by pressing 'Enter' after writing number in the terminal input. A simple workaround is to read the '\n' character using input.nextLine() and ignore it immediately after you use Scanner.nextX() methods (eg. nextInt(), nextDouble(), etc.)

So your code changes to this:

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();
    } 
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27115&siteId=1