随机数字随机生成器,随机数落后于错误

时间:2013-09-11 21:57:37

标签: 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();

}
}

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);