The first and last name MUST BE PRINTED ON THE SAME LINE by the user per instruc
ID: 3619608 • Letter: T
Question
The first and last name MUST BE PRINTED ON THE SAME LINE by the user per instructions. It's assumed that correct punctuation's used for everything except the name. What I have so far...import java.util.*;
public class MadLibs {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the following information: ");
System.out.println("Enter your first and last name: ");
String fname = keyboard.next();
int x = fname.length();
String name2 = fname.substring(0,1).toUpperCase().concat(fname.substring(1, x).toLowerCase());
String lname = keyboard.nextLine();
String name3 = lastname(lname);
System.out.println("Enter your hometown city,hometown state: ");
String home = keyboard.nextLine();
System.out.println("Enter your age as an integer: ");
int age = keyboard.nextInt();
keyboard.nextLine();
System.out.println("Enter a profession: ");
String job = keyboard.nextLine();
System.out.println("There once was a person named " + name2 + " " + name3 + " who lived in " + home + ".");
System.out.println("At the age of " + age + ", " + name2 + " went to Stanford and took Bio101.");
System.out.println(name2 + " later graduated and went to work as a successful " + job + ".");
}
public static String lastname(String lname){
int y = lname.length();
String name3 = lname.substring(0,1).toUpperCase().concat(lname.substring(1, y).toLowerCase());
return name3;
}
....What I want to print out....
Please enter the following information:
Enter your first and last name:
Bob Melvin
Enter your hometown city,hometown state:
Stanford, California
Enter your age as an integer:
18
Enter a profession:
oceanographer
There once was a person named Bob Melvin who lived in Stanford, California.
At the age of 18, Bob went to Stanford and took Bio101.
Bob later graduated and went to work as a successful oceanographer.
Explanation / Answer
You can use a common function something like this: Pass the name string as s variable public static String capitalizeFirstLettersTokenizer ( String s ) { final StringTokenizer st = new StringTokenizer( s, " ", true ); final StringBuilder sb = new StringBuilder(); while ( st.hasMoreTokens() ) { String token = st.nextToken(); token = String.format( "%s%s", Character.toUpperCase(token.charAt(0)), token.substring(1) ); sb.append( token ); } return sb.toString(); } Note: With this method you can pass the whole of the sentence and all the whitespace separated characters would be capitalized. Otherwise you can use some custom made code like: Use capitalize() function defined in WordUtils class. But you need to import :import org.apache.commons.lang.WordUtils; Hope this helps
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.