public class Methods {
public static void main(String[] args) {
printNumbers(1, 10, 2);
printNumbers(-10, 0, 3);
String str = "aardvarks don't eat bananas";
System.out.println("The string \"" + str + "\" has " + countA(str)
+ " letters a");
System.out.println(interleave('*', "MASH"));
System.out.println(replace("abca", 'a', 'x'));
System.out.println(hasCharacter("banana",'n'));
System.out.println(hasCharacter("banana",'e'));
printsEveryOther("Data Structures");
}
/**
* Parameters: three integers: start, bound, and skip. The method prints
* numbers starting at start, no larger than bound, incrementing by skip.
* The numbers are printed on a single line, then a new line is printed.
**/
public static void printNumbers(int start, int bound, int skip) {
for (int i = start; i <= bound; i = i + skip) {
System.out.print(i + " ");
}
System.out.println();
}
/**
* Parameters: String s. The method takes a String and returns the number of
* lower-case letters 'a' in the string.
**/
public static int countA(String s) {
int count = 0;
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j) == 'a') {
count++;
}
}
return count;
}
public static String interleave(char i, String str){
String s = "";
for(int n = 0; n < str.length(); n++){
s = s + str.charAt(n) + i;
}
return s;
}
public static String replace(String str, char a, char b){
String s ="";
for(int n = 0; n < str.length(); n++){
if (str.charAt(n) == a){
s = s + b;
} else {
s = s + str.charAt(n);
}
}
return s;
}
public static boolean hasCharacter(String str, char c) {
for (int i = 0; i < str.length(); i++){
if ( str.charAt(i) == c) {
return true;
}
}
return false;
}
public static void printsEveryOther(String s) {
for (int i = 0; i < s.length(); i = i + 2) {
System.out.print(s.charAt(i));
}
System.out.println();
}
}
Write a method interleave
that takes a character and a string and
returns a string that has the character interleaved after each
character in the given string. For instance, interleave("abc",
'*')
returns "a*b*c*"
.
Write a method replace
that takes a string and
two characters and returns a string in which every occurrence of the
first character is replaced by the second one. For
instance, replace("a cat is cute", 'c', '*')
results in
"a *at is *ute"
Write a method hasCharacter
that takes a string and a
character and returns true if the character occurs in the string and
false otherwise.
Write a method printEveryOther
that takes a string and
prints its every other character, starting with the first one.