1

我已经研究了大约一个小时,我真的无法弄清楚这一点,我想制作一些提示并读取用户的名字和姓氏(分别)的东西。然后打印一个字符串,该字符串由用户名的第一个字母,后跟用户姓氏的前五个字符,后跟一个 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();

}
}
4

2 回答 2

0

这将在您的代码末尾打印想要的内容,不错的开始,继续努力

谁能弄清楚这部分?我正在练习 (:

然后,如果您愿意,可以对其进行增强,如果姓氏长度小于 5 个字符,它会插入额外的随机字符或数字,以便生成的用户名仍然包含 8 个字符。这是一个可选的增强功能。

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(concatenatedName);
于 2015-02-15T08:17:08.730 回答
0

您应该尝试这样的事情来处理姓氏长度可能不是 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);
于 2013-09-11T22:21:27.597 回答