Question

I'm attempting to get user input and print out the first name + 5 characters from the last name followed by random numbers. I'm really new to Java and I've been able to get user input and make the random number but I'm not quite sure how I should format the printf to only get 5 characters from my second string. I'm not even 100% sure printf is what I'm looking for.

Scanner name = new Scanner (System.in);

String firstname;
String secondname;
System.out.println("Enter your first name:");
firstname = name.next();
System.out.println("Enter your last name:");
secondname = name.next();

Is how I'm getting user input for their first and last name.

edit: I'm supposed to assume the last name has more than 5 characters

Was it helpful?

Solution 2

If you were looking to display up to five characters from the last name (secondname), you can use substring:

System.out.println(secondname.substring(0, Math.min(5, secondname.length())));

Therefore, your final output would be something like this:

// Import 'java.util.Random' at the top of your file

Random rand = new Random();
int max = 9999;
int min = 1000;
int rnd = rand.nextInt((max - min) + 1) + min;

String fullString = firstname
    + secondname.substring(0, Math.min(5, secondname.length()))
    + String.valueOf(rnd);

OTHER TIPS

You can use String.substring to get a portion of your String.

System.out.println(secondname.substring(0,5));

Remember to check the actual length first, otherwise you'll throw a StringIndexOutOfBoundsException.

Also remember to check for nulls.

This will do the trick

    String secondname = "sdrias";
    String firstname = "rasdgfdsg";
    String combinedString = "";
    if(secondname.length() < 5) {
       combinedString = firstname+secondname;
    } else {
       combinedString = firstname+secondname.substring(0, 5);
    }

    System.out.println(combinedString);

Something, like this:

String result = firstname + ((secondname.length() > 5) ? secondname.substring(0, 5) : secondname) + random;

This code checks secondname length, and if secondname is shorter than 5 chars, it will be appended fully. random - is your random number. result will contain exactly what you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top