-1

How do I check if scanner input is blank and assign a variable to the blank string? Overwriting the initial String?

Tried the following code and it does not work.

System.out.print("Username: ");

    String username = sc.nextLine();

    int u1nameLength = username.length();

    if (u1nameLength == 0) {

        String username = "Dude"; //generate replacement username

    }

    System.out.print("Phone Number: ");

    String phoneNumber = sc.nextLine();
JavaNoob
  • 1
  • 2

1 Answers1

0

You only need to reassign the variable, not redeclare it

if (username.isEmpty()) {
   username = "Dude"; //generate replacement username
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Yes I should not have written String at the beginning. Removed it and it worked. Thanks! – JavaNoob Sep 08 '19 at 06:16
  • One more thing. What is the best way to generate a string of about 10 random lowercase letters to become username, instead of using predefined "Dude"? – JavaNoob Sep 08 '19 at 06:28
  • @JavaNoob to generate random string you can refer to this [question](https://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string). – Mushif Ali Nawaz Sep 08 '19 at 06:53