Reputation: 1
So I'm new to coding and my teacher asked us to make a code that does this. I need to use substring to do it.
This is what I have to do.
Example output 1: Welcome to the twist around (made up language) translation program.
Enter word to translate: Helicopter Word in twistaround: OpterhelicCR
Example output 2: Welcome to the twist around (made-up language) translation program.
Enter word to translate: Hello Word in twist around: LohelLO
Notes: Translated words are formed like this: Helicopter = OpterhelicCR First letter of the second half in uppercase: Opter First letter of the first half in lower case: helic Last letter of the first half in uppercase: C Last letter of the second half in uppercase: R
This is my code. public static void main(String[] args) { Scanner input = new Scanner(System.in);
System.out.println("Welcome to the twistAround (made up language) translation program.\n");
System.out.print("Enter word to translate: ");
String word = input.nextLine();
String secondHalf = word.substring(word.length() / 2, word.length());
System.out.println(secondHalf);
Output: Welcome to the twistAround (made up language) translation program.
Enter word to translate: Helicopter opter BUILD SUCCESSFUL (total time: 4 seconds)
So far, I've got it to output opter. However, I'm not sure how I would capitalize the "o".
Upvotes: 0
Views: 403
Reputation: 3728
the use of a StringBuilder
prevents the unnecessary generation of strings
String secondHalf = "opter";
StringBuilder buf = new StringBuilder( secondHalf );
buf.setCharAt( 0, Character.toUpperCase( buf.charAt( 0 ) ) );
buf.toString(); // "Opter"
secondHalf
may not be empty
otherwise a java.lang.StringIndexOutOfBoundsException
is thrown
Upvotes: 0
Reputation: 2670
1 - one way to use charAt method and get the first character.
2 - change the case of character and add it to string.
String secondHalf = "opter";
char a = secondHalf.charAt(0);
secondHalf = secondHalf.substring(1);
secondHalf = Character.toString(a).toUpperCase()+secondHalf;
System.out.println(secondHalf);
3 - one other way to use substring method and then remove first character. changer the case. then add it to string.
String secondHalf = "opter";
String a = secondHalf.substring(0, 1);
secondHalf = secondHalf.substring(1);
secondHalf = a.toUpperCase()+secondHalf;
System.out.println(secondHalf);
Upvotes: 0