简体   繁体   中英

How to generate a random number if there is no input from the keyboard

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM