For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.
The Warmup-2 section on CodingBat gently introduces string and array loops. There wasn’t much to comment since the solutions are all relatively straight-forward. All solutions were successfully tested on 13 January 2013.
stringTimes:
public String stringTimes(String str, int n) {
String result = “”;
for (int i = 0; i < n; i++)
result += str;
return result;
}
[/sourcecode]frontTimes:
public String frontTimes(String str, int n) {
String result = “”;
if (str.length() <= 3)
for (int i = 0; i < n; i++)
result += str;
else
for (int i = 0; i < n; i++)
result += str.substring(0, 3);
return result;
}
[/sourcecode]countXX:
int countXX(String str) {
int count = 0;
for (int i = 0; i < str.length() - 1; i++)
if (str.substring(i, i + 2).equals("xx"))
count++;
return count;
}
[/sourcecode]doubleX:
boolean doubleX(String str) {
int firstX = str.indexOf(‘x’);
if (firstX < str.length() - 1)
return str.charAt(firstX + 1) == 'x';
return false;
}
[/sourcecode]stringBits:
public String stringBits(String str) {
String result = “”;
for (int i = 0; i < str.length(); i++) {
if (i % 2 == 0)
result += str.charAt(i);
}
return result;
}
[/sourcecode]stringSplosion:
public String stringSplosion(String str) {
String result = “”;
for (int i = 0; i <= str.length(); i++) {
result += str.substring(0, i);
}
return result;
}
[/sourcecode]last2:
public int last2(String str) {
int count = 0;
for (int i = 0; i < str.length() - 2; i++) {
if (str.substring(i, i + 2).equals(
str.substring(str.length() - 2)))
count++;
}
return count;
}
[/sourcecode]arrayCount9:
public int arrayCount9(int[] nums) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 9)
result++;
}
return result;
}
[/sourcecode]arrayFront9:
public boolean arrayFront9(int[] nums) {
int check = (nums.length < 4) ? nums.length : 4;
for (int i = 0; i < check; i++) {
if (nums[i] == 9) return true;
}
return false;
}
[/sourcecode]I use the ternary operator for the sake of brevity. You can of course expand the assignment operation into an if/else block.array123:
public boolean array123(int[] nums) {
for (int i = 0; i < nums.length - 2; i++)
if (nums[i] == 1 && nums[i + 1] == 2 && nums[i + 2] == 3)
return true;
return false;
}
[/sourcecode]
For further help with Coding Bat (Java), please check out my books. I am also available for tutoring.