Write a program in a single class called DoubleLetters that does the following:
ID: 3670641 • Letter: W
Question
Write a program in a single class called DoubleLetters that does the following:
The program should read in a single line of text from the keyboard. It should then print to the console the same line of text, only now with every letter doubled. Other characters, such as numbers, spaces, and punctuation in the line should be left alone, except for exclamation points (!): These should be tripled.
The objectives of this assignment are to:
Be able to read text input from the keyboard using a Scanner object.
Be able to traverse the characters in a String using String class methods and a for loop.
Be able to use an if statement in a loop.
Example 1: if the input text is:
Then your program should print:
Example 2: if the input text is:
Then your program should print:
Hint:
When is a character a letter? There is more than one way to tell. Look up the Character class in the Java API. There is a method that would be very helpful.
Submit your code for the DoubleLetters class below. Do NOT include import statements in your submission. We import the Scanner class for you.
import java.util.Scanner;
Explanation / Answer
HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
DoubleLetters dl = new DoubleLetters();
dl.DoDoubling();
}
}
DoubleLetters.java
import java.util.Scanner;
public class DoubleLetters {
private final char SPECIAL_CHAR_EXCALAM = '!';
public void DoDoubling() {
Scanner in = new Scanner(System.in);
String input = in.nextLine();
int length = input.length();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
sb.append(input.charAt(i));
if (isAlphabet(input.charAt(i))) {
sb.append(input.charAt(i));
}
if (input.charAt(i) == SPECIAL_CHAR_EXCALAM) {
sb.append(input.charAt(i));
sb.append(input.charAt(i));
}
}
System.out.println(sb);
}
private boolean isAlphabet(char chr) {
int asciiChar = chr;
return (asciiChar >= 65 && asciiChar <= 90)
|| (asciiChar >= 97 && asciiChar <= 122);
}
}
output
Hey My car an't move
HHeeyy MMyy ccaarr aann'tt mmoovvee
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.