# CodingBat: Java. Warmup-2, Part I

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;
}
```

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;
}
```

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;
}
```

doubleX:

```boolean doubleX(String str) {
int firstX = str.indexOf('x');
if (firstX < str.length() - 1)
return str.charAt(firstX + 1) == 'x';
return false;
}
```

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;
}
```

stringSplosion:

```public String stringSplosion(String str) {
String result = "";
for (int i = 0; i <= str.length(); i++) {
result += str.substring(0, i);
}
return result;
}
```

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;
}
```

arrayCount9:

```public int arrayCount9(int[] nums) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 9)
result++;
}
return result;
}
```

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;
}
```

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;
}
```

## 2 thoughts on “CodingBat: Java. Warmup-2, Part I”

1. Christopher Stigson

For string times I put:

def string_times(str, n):
if int(n) >= 0:
return str * n

And it worked. Gave me all correct. is this wrong?