Reputation: 11
I need to write a small program that takes in a string like Hello World and prints out HHHEEELLLOOO WWWOOORRRLLLDDD, but instead of just hello world it would take in any string using the scanner function and produce the same result. I am new to java and cannot figure out how to create this program at all.
Upvotes: 0
Views: 3590
Reputation: 2021
int No_of_Repeats = 2;
Scanner sc = new Scanner(System.in);
String user_input=sc.next();
for (int i = 0; i < user_input.length(); i++) {
char c = input.charAt(i);
for (int j = 0; j < No_of_Repeats; j++) {
result+=c;
}
}
return result;
Upvotes: 0
Reputation: 22415
They key to learning how to program is to break up the problem into smaller pieces.
Write a program, using Scanner
, to echo back the input and exit.
Modify that program so that you loop over the input and print each character.
Modify that program to print each character twice.
Modify that program to print each character n
number of times.
Upvotes: 3
Reputation: 2731
I would do it like this at the first thought, but there may be an easier solution saving all the concatenations.
String produceString(String source, int numberPerLetter) {
String result = "";
for (int i = 0; i < source.length(); i++) {
char c = source.charAt(i);
for (int j = 0; j < numberPerLetter; j++) {
result += c;
}
}
return result;
}
Upvotes: 2
Reputation: 10151
Get the string from whichever source you want, e.g. scanner. Then iterate over each character in the string and print it as many times as you want.
int charRepeats = 3;
String input = "Whatever"; // Get from whichever source you want.
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
for (int j = 0; j < charRepeats; j++) {
System.out.print(c);
}
}
Upvotes: 0