The Java Learning Project

I started learning Java programming and found a perfect website for practicing: Codingbat.com. CodingBat is a free site of live coding problems to build coding skill in Java and Python. CodingBat is a project by Nick Parlante, a computer science lecturer at Stanford.

I will upload my solutions here.

Given an array of ints, return the number of times that two 6's are next to each other in the array. Also count instances where the second "6" is actually a 7. 

array667([6, 6, 2]) → 1
array667([6, 6, 2, 6]) → 1
array667([6, 7, 2, 6]) → 1

1
2
3
4
5
6
7
8
public int array667(int[] nums) {
  int count=0;
  for (int i=0; i<nums.length-1;i++){
    if ((nums[i]==6) && ((nums[i+1]==6) || (nums[i+1]==7))){
      count++;
    }
  }return count;
}

Suppose the string "yak" is unlucky. Given a string, return a version where all the "yak" are removed, but the "a" can be any char. The "yak" strings will not overlap.

stringYak("yakpak") → "pak"
stringYak("pakyak") → "pak"
stringYak("yak123ya") → "123ya"

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public String stringYak(String str) {
         String result="";
        for (int i=0; i<=str.length()-1; i++){
            if ((i<=str.length()-3) && ((str.substring(i,i+1)).equals("y")) && ((str.substring(i+2,i+3)).equals("k"))) {
                i=i+2;
            }else{
                result=result+str.substring(i,i+1);
            }
        }return result;
}

Keresés

Ajánló