141k views
5 votes
Write a Java program to simulate a "mexican wave" on a String. Within your program, create a method called wave which takes one String as an input. This method should return an array of stages in the wave.

User Naseema
by
7.9k points

1 Answer

4 votes

Final answer:

To simulate a 'Mexican wave' on a String in Java, you can create a method called wave that takes a String as input and returns an array of stages in the wave.

Step-by-step explanation:

To simulate a 'Mexican wave' on a String in Java, you can create a method called wave that takes a String as input and returns an array of stages in the wave. Here's a step-by-step explanation:

  1. Create a method called 'wave' that takes a String as input.
  2. Inside the 'wave' method, initialize an empty ArrayList to store the stages of the wave.
  3. Loop through each character in the input string.
  4. For each character, check if it's a letter or whitespace.
  5. If it's a letter, create a new string where the character is capitalized, and concatenate it with the remaining substring from the input string.
  6. Add this new string to the ArrayList.
  7. After the loop, convert the ArrayList to an array and return it.

Here's an example implementation:

import java.util.ArrayList;

public class MexicanWave {

public static String[] wave(String str) {
ArrayList stages = new ArrayList<>();

for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);

if (Character.isLetter(ch) || ch == ' ') {
String waveStr = Character.toUpperCase(ch) + str.substring(i + 1);
stages.add(waveStr);
}
}

return stages.toArray(new String[0]);
}

public static void main(String[] args) {
String input = "hello world";
String[] waveStages = wave(input);

for (String stage : waveStages) {
System.out.println(stage);
}
}

}

User Casteurr
by
8.1k points