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.

Start with 2 int arrays, a and b, each length 2. Consider the sum of the values in each array. Return the array which has the largest sum. In event of a tie, return a.

biggerTwo([1, 2], [3, 4]) → [3, 4]
biggerTwo([3, 4], [1, 2]) → [3, 4]
biggerTwo([1, 1], [1, 2]) → [1, 2]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public int[] biggerTwo(int[] a, int[] b) {
  int sum_a;
  int sum_b;
  sum_a=a[0]+a[1];
  sum_b=b[0]+b[1];
  if (sum_a>=sum_b){
    return a;
  }else{
    return b;
  }
}

Given an int array length 2, return true if it contains a 2 or a 3.

has23([2, 5]) → true
has23([4, 3]) → true
has23([4, 5]) → false

1
2
3
public boolean has23(int[] nums) {
  return ((nums[0]==2) || (nums[1]==2) || (nums[0]==3) || (nums[1]==3));
}

Given a string, if one or both of the first 2 chars is 'x', return the string without those 'x' chars, and otherwise return the string unchanged. This is a little harder than it looks.

withoutX2("xHi") → "Hi"
withoutX2("Hxi") → "Hi"
withoutX2("Hi") → "Hi"

1
2
3
4
5
6
7
8
public String withoutX2(String str) {
  String result="";
  for (int i=0; i<=str.length()-1;i++){
    if ( !(i==0 || i==1) || !(str.substring(i,i+1).equals("x")) ){
      result=result+str.substring(i,i+1);
    }
  }return result;
}

Keresés

Ajánló