PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

[FIXED] How to input an Empty string in JAVA

 October 28, 2022     is-empty, java, next, string     No comments   

Issue

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.


Solution

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


Answered By - Meet Sinojia
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing