Java Program Write a program in a single class called DoubleLetters that does th
ID: 3586094 • Letter: J
Question
Java Program
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 with these changes: Letters should be doubled. Exclamation points (!) should be tripled. All other characters appear as they do in the input string.
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:
note: concatenating a char onto a String requires that you add an empty String so the char is treated as a character and not a number. Example: newStr = newStr + "" + curChar;
Another approach: simply print the answer character by character as you traverse the input string.
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
public class DoubleLetters {
private String inputString;
private String outputString ="";
private void getString()
{
Scanner sc = new Scanner(System.in);
inputString = sc.nextLine();
}
private void parseString()
{
int length = inputString.length();
int index = 0;
while (index<length)
{
char c = inputString.charAt(index);
if(c==33) //ascii value of !
{
outputString = outputString+c+c+c;
}
else if(c>=65 && c<=122)
{
outputString = outputString+c+c;
}
else
{
outputString = outputString+c;
}
index++;
}
}
private void showString()
{
System.out.println("The output string is: "+outputString);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
DoubleLetters dobj = new DoubleLetters();
dobj.getString();
dobj.parseString();
dobj.showString();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.