首页 > 解决方案 > Use random name generator after getting input from keyboard

问题描述

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
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[] randoms = {"Luke", "Leia", "Sophia", "David"};
                name = randoms[((int) Math.random()*randoms.length)];
            }
            
            System.out.println("" + user_Name1);
            
    }
    
}

标签: java

解决方案


这应该做的工作:

// Starting in main function after the System.out.println()

String name = scanner.nextLine();
scanner.close(); // optional but recommended

if (name == null || name.equals("") {
    // Do random pick as you did before and assign it to name
    String[] randoms = {"Luke", "Leia", "Sophia", "David"}; // Add all names here
    name = randoms[((int) Math.random()*randoms.length)]; // Pick random name
}

System.out.println("Your name is " + name);

// The rest of the class with closing brackets

推荐阅读