exercism————Hamming

题目:

exercism————Hamming_第1张图片

解法

package exercism;

public class Hamming {
     
	public int hammingDistance = 0;
	static final char[] dnaElements = {
     'G','A','C','T'};

	public Hamming(String DNA1, String DNA2) throws InvalidDNAException {
     
		if (DNA1 == null || DNA2 == null) {
     
			throw new IllegalArgumentException(" DNA can not be null");
		}


		if (!checkIfVaild(DNA1,DNA2)) {
     
			throw new InvalidDNAException("Invalid DNA Sequence ");
		}




		for (int i = 0; i <DNA1.length() ; i++) {
     
			if (DNA1.charAt(i) != DNA2.charAt(i)) {
     
				this.hammingDistance +=1;
			}
		}

	}

	boolean checkIfVaild (String DNA1, String DNA2) {
     
		// check the length of DNA1 and DNA2
		if (DNA1.length() != DNA2.length()) {
     
			return false;

		}

		// check if DNA1 and DN2 only contains 'G' 'A' 'C' 'T'
		for (int i = 0; i < DNA1.length(); i++) {
     
			if (!contains(DNA1.charAt(i))) {
     return false;}
		}

		for (int i = 0; i < DNA2.length(); i++) {
     
			if (!contains(DNA2.charAt(i))) {
     return false;}
		}

			return true;

	}

	/**
	 * check if a char belong to {G,A,C,T}
	 * @param c
	 * @return
	 */

	boolean contains(char c) {
     
		for (int i = 0; i < dnaElements.length; i++) {
     
			if (dnaElements[i] == c) {
     
				return true;
			}
		}
			return false;
	}

}
package exercism;

public class InvalidDNAException extends Exception {
     
	public InvalidDNAException(String message) {
     
		super(message);
	}
}

总结:

mentor很有耐心,一共改了九次才给过哈哈,每次都会提出一些小小的建议来帮助我改进,国外的社区技术氛围太好了,下面就来总结下吧:

  • Always check the input before assign them or assign them as attributes
  • Check the method siginature and if the paramater is null,or will the paramater will be something unexpect
  • When should we store a variable as a atributes,is it a need to store a variable when we can’t modify them?
  • Don’t forget to initialize variable although it will automatically assign them default value,but it is more straghtforward and clear to initialize
  • When you enter in a method, you should always start by checking the inputs. It is even more important in a constructor

你可能感兴趣的