tom
tom

Reputation: 11

duplicate characters in a loop

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

Answers (4)

Venugopal Madathil
Venugopal Madathil

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

Jeremy
Jeremy

Reputation: 22415

They key to learning how to program is to break up the problem into smaller pieces.

  1. Write a program, using Scanner, to echo back the input and exit.

  2. Modify that program so that you loop over the input and print each character.

  3. Modify that program to print each character twice.

  4. Modify that program to print each character n number of times.

Upvotes: 3

S&#246;ren
S&#246;ren

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

DaveJohnston
DaveJohnston

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

Related Questions