0

I have been given help on how to generate a random name if input from keyboard is "". How do I do the same to generate a random number if input is ""? input "please enter the first number: " out - if no value is entered "" then generate random number.

package username;

import java.util.Scanner;
import java.util.Random;

public class UserName {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        String user_Name1;
        System.out.print("Please enter the first username: ");
        user_Name1 = input.nextLine();
        if (user_Name1.equals("")) {
            String[] random = {"Luke", "Leia", "Hans", "Darth" , "Vader" , "Chewbacca"};
            user_Name1 = random[(int) (Math.random() * random.length)];
        }

        System.out.println("" + user_Name1);

        System.out.print("Please enter the first number: ");
        int user_number1 = input.nextInt();
    }
}
khelwood
  • 46,621
  • 12
  • 59
  • 83
Paul
  • 1
  • 4
  • Possible duplicate of [How do I generate random integers within a specific range in Java](https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java) – RMPR Feb 20 '20 at 09:15
  • 1
    Does this answer your question? [How do I generate random integers within a specific range in Java?](https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java) – RMPR Feb 20 '20 at 09:15
  • Do you understand what your current code does? What `(Math.random() * random.length)` does? That's all you need. – Amongalen Feb 20 '20 at 09:15
  • hi @Amongalen to be honest i dont- would you be kind enough to explain? – Paul Feb 20 '20 at 09:23
  • @Amongalen to be honest i don't really understand that line of code. Could you explain please? – Paul Feb 20 '20 at 09:32

1 Answers1

0

Here input.nextInt(); means Scanner.nextInt is not taking enterkey as an valid input. So you can try by input.nextLine() and casting the value to an Integer.

Dale K
  • 16,372
  • 12
  • 37
  • 62
V_K
  • 196
  • 10