How to write Java String Program more succinctly
Below is a program I've written for a beginning Java course. The user
inputs their first and last name and it changes the names to Pig Latin.
The program runs fine, output is perfect but I wanted to take this further
and make the code shorter and easier to read. (Because I'm really new to
this, my code isn't the most elegant but I'd like to change that.) I built
in a default to make the first and last all lowercase so it wouldn't mess
up the end product (I'm not sure if this is necessary). (Our teacher wants
just the first letter moved to the last, add "ay" to end of each name and
capitalize the first letter of each new pig latin name.)
package pkg5003_program2;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
//user input first name
System.out.print("Enter First Name:" );
Scanner scanFirst = new Scanner(System.in);
String firstName = scanFirst.next();
//default first name to all lower case
String firstLowerCase = firstName.toLowerCase();
//initialize "ay" string
String ay = new String("ay");
//switch first letter to last
String newFirst = firstLowerCase.substring(1) +
firstLowerCase.charAt(0);
//add ay string
String pigLatFirst = newFirst.concat(ay);
//user input last name
System.out.print("Enter Last Name:" );
Scanner scanLast = new Scanner(System.in);
String lastName = scanLast.next();
//default last name to all lower case
String lastLowerCase = lastName.toLowerCase();
//switch first letter to last
String newLast = lastLowerCase.substring(1) +
lastLowerCase.charAt(0);
//add ay string
String pigLatLast = newLast.concat(ay);
//change first letter to uppercase for first name
String finalFirst = pigLatFirst.substring(0,1).toUpperCase() +
pigLatFirst.substring(1);
//change first letter to uppercase for last name
String finalLast = pigLatLast.substring(0,1).toUpperCase() +
pigLatLast.substring(1);
//print output
System.out.println("In Pig latin your name is: " + finalFirst
+ " " + finalLast);
System.out.println("Program written by Ashley Dinatale");
}
}
No comments:
Post a Comment