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 a string of any length, return a new string where the last 2 chars, if present, are swapped, so "coding" yields "codign".

lastTwo("coding") → "codign"
lastTwo("cat") → "cta"
lastTwo("ab") → "ba"

1
2
3
4
5
6
7
8
public String lastTwo(String str) {
  String result="";
  if (str.length()>=2){
    result=str.substring(0,str.length()-2)+str.substring(str.length()-1,str.length())+str.substring(str.length()-2,str.length()-1);
  }else{
    result=str;
  }return result;
}

Given two strings, append them together (known as "concatenation") and return the result. However, if the concatenation creates a double-char, then omit one of the chars, so "abc" and "cat" yields "abcat".

conCat("abc", "cat") → "abcat"
conCat("dog", "cat") → "dogcat"
conCat("abc", "") → "abc"

1
2
3
4
5
6
public String conCat(String a, String b) {
  if ((a.length()!=0) && (b.length()!=0) && ((a.substring(a.length()-1,a.length())).equals(b.substring(0,1)))){
    return a+b.substring(1,b.length());
  }
  return a+b;
}

Given an array of ints, we'll say that a triple is a value appearing 3 times in a row in the array. Return true if the array does not contain any triples.

noTriples([1, 1, 2, 2, 1]) → true
noTriples([1, 1, 2, 2, 2, 1]) → false
noTriples([1, 1, 1, 2, 2, 2, 1]) → false

1
2
3
4
5
6
7
8
public boolean noTriples(int[] nums) {
  boolean triples=true;
  for (int i=0;i<=nums.length;i++){
    if ((i<=nums.length-3) && (nums[i]==nums[i+1]) && (nums[i]==nums[i+2])){
      triples=false;
    } 
  }return triples;
}

Keresés

Ajánló