I have been on this for about an hour and I really can't figure this out, I am suppose to make something that prompts for and reads the user's first and last name (separately). Then print a string composed of the first letter of the user's first name, followed by the first five characters of the user's last name, followed by a random number in the range 10 to 99. and assume that the last name is at least five letters long
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();
}
}
You should try something like this to deal with the fact the lastname might not be 5 characters in length. The latter part of your function - where you set check the length and add another random number is not required.
// 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);
This will print what wanted at the end of your code, not a bad start, keep up the hard work
can anyone figure out this part? I am practicing (:
Then, if you like, enhance it so that if the last name is less than 5 characters long, it inserts extra random characters or digits so that the generated user name still contains 8 characters. This is an optional enhancement.
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);
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.