java - 随机用户名生成器,带有错误背后的随机数

标签 java

我已经研究了大约一个小时,我真的无法弄清楚这一点,我想制作一些提示并读取用户的名字和姓氏(分别)的东西。然后打印一个由用户名字的第一个字母、用户姓氏的前五个字符和 10 到 99 范围内的随机数组成的字符串。并假设姓氏至少有五个字母长

import java.util.Scanner;  //Needed for the Scanner class  
import java.lang.String;

import java.util.Random;

public class UsernameGenerator
{    
public static void main(String[] args)  //all the action happens here!    
{  Scanner input = new Scanner (System.in);
    Random generator = new Random();

    int num1;
    num1 = generator.nextInt(10-99);

    String firstName;
    String lastName;
    String concatenatedName;

    System.out.println("Enter your First Name: ");
    firstName = input.next();



    System.out.print( "Enter your Last Name: " );
    lastName = input.next();


    // We'll take the first character in the first name
    concatenatedName = firstName.charAt(0) + lastName.substring(0, 5) + num1;



    Random rnd = new Random(); // Initialize number generator
    if (lastName.length() > 5)
        concatenatedName += lastName.substring(0,5);
    else
        concatenatedName += lastName; // You did not specify what to do, if the name is shorter than 5 chars

    concatenatedName += Integer.toString(rnd.nextInt(99));


    System.out.println();

}
}

最佳答案

您应该尝试类似的方法来处理姓氏长度可能不是 5 个字符的事实。函数的后半部分 - 不需要设置检查长度并添加另一个随机数。

    // We'll take the first character in the first name
    try
    {
        concatenatedName = firstName.charAt(0) + lastName.substring(0, 5) + num1;
    }
    catch (Exception e)
    {
        // Here we deal with the fact we might not be able to get 5 characters from the last name
        // - Just add the full lastname
        concatenatedName = firstName.charAt(0) + lastName + num1;
    }

    System.out.println(concatenatedName);

关于java - 随机用户名生成器,带有错误背后的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18751997/

相关文章:

java - Facebook 点赞按钮的说明

java - 在同一事务中锁定的节点之间创建关系的 Neo4j 死锁

java - jpackage 创建 2 个 JRE 副本

java - 如何使用 GSON 从 Primeface 应用程序下载 json 文件?

java - 脂肪 jar 立即关闭

java - 使用 HTTPUrlConnection 的 RESTful 请求

java - JNA 联合结构映射

java - 对象数组列表 - 最小值

java - 将数据库中的日期与我从java jsp和sql中的inputtext获得的值进行比较

java - 无法为hadoop指定kerberos的配置位置