3

I know this doesnt work but how can I know if the user added even one char?

public class Program
import java.util.Scanner;
{
public static void main(String[] args) {
    Scanner a = new Scanner(System.in);
    String b = a.nextLine();

//I know this doesnt work but how can I know if the user added even one char?
    if (b!=null){
    System.out.println(b);
}
}
}
Víťa Dvořák
  • 33
  • 1
  • 1
  • 4
  • 1
    You can check [String.length](https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#length--) ... and [String.isEmpty()](https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#isEmpty--) is equivalent to checking length for 0. – Fildor Jan 24 '18 at 08:20
  • `b.isEmpty()`. `nextLine()` never returns null. – Andy Turner Jan 24 '18 at 08:21
  • Mind that Whitespaces count for length. So if you actually want to check for "Non-Whitespace characters" then there is a little more effort. See also: https://stackoverflow.com/a/3247081/982149 – Fildor Jan 24 '18 at 08:27

2 Answers2

6

you can use .equals("") or .isEmpty()

check check if the variable is null

SF..MJ
  • 862
  • 8
  • 19
  • Why you'd even suggest `equals("")` when `String` has `isEmpty()` is beyond me. – Sync Jan 24 '18 at 08:55
  • because you can use `equals("")` also as it is from parent calss `Object` but you are right , better to use `isEmpty()` because ,see The main benefit of `"".equals()` is you don't need the null check (equals will check its argument and return false if it's null), which you seem to not care about. If you're not worried about `b` being null (or are otherwise checking for it), I would definitely use `.isEmpty()`; it shows exactly what you're checking, you care whether or not `b` is empty, not whether it equals the empty string – SF..MJ Jan 24 '18 at 09:12
  • Your answer advocates `.equals("")` not `"".equals(s)`. It also did not include the advantages of using `"".equals(s)`. Are you expecting this to come naturally to the readers who read your answer but not the comments? I still stand by that this is a bad answer. – Sync Jan 24 '18 at 09:52
  • i am not telling you the advantages am telling you how many ways we can check..so `.equals()` is also one of them – SF..MJ Jan 24 '18 at 12:59
0

You can do this

if (!b.isEmpty()) {
  System.out.println(b);
}