Skip to content

Instantly share code, notes, and snippets.

@timkaechele
Created November 9, 2014 10:05
Show Gist options
  • Save timkaechele/c9f3773bcb1598d517d7 to your computer and use it in GitHub Desktop.
Save timkaechele/c9f3773bcb1598d517d7 to your computer and use it in GitHub Desktop.
Math Exercise 4 Task 5a Java Version
/**
* ISBN Class
* Represents an ISBN can check its correctness and
* complete an partial ISBN
* @author Tim Kächele
* @copyright Copyright (c) 2014 Tim Kächele
* @license MIT License
*/
import java.util.ArrayList;
import java.util.Collections;
public class Isbn {
private ArrayList<Integer> list;
/**
* Initialize the class
*
* @param integer an ISBN
*/
public Isbn(int integer) {
this.list = integerToList(integer);
}
/**
* Validates the correct length of the ISBN
*
* @return boolean with the correct length of the ISBN
*/
public boolean isComplete(){
return this.list.size() == 10;
}
/**
* Validates the correctness of an ISBN
* returns false if the ISBN is inomplete
*
* @return boolean with the correctness of the ISBN
*/
public boolean isCorrect(){
if (!this.isComplete()) {
return false;
} else {
return (this.sum() % 11) == 0;
}
}
/**
* Checks if the ISBN is incomplete and completes
* the ISBN if necessary.
*/
public void complete(){
if(this.list.size() == 9) {
this.list.add(this.calcLastDigit());
}
}
/**
* Calculates the last digit of an ISBN
*
* @return value of the last digit
*/
private int calcLastDigit(){
return this.sum() % 11;
}
/**
* Generates a string with the ISBN
* Replaces the last digit with X if the digit is 10
*
* @return ISBN string
*/
public String toString(){
String string = "";
int integer;
for (int i = 0; i < this.list.size() ; i++) {
integer = this.list.get(i);
if(integer == 10) {
string += "X";
} else {
string += integer;
}
}
return string;
}
/**
* Converts an integer to a list
*
* @param integer ISBN integer
* @return ArrayList with the integers of the ISBN
*/
private static ArrayList integerToList(int integer) {
ArrayList<Integer> list;
list = new ArrayList<Integer>();
while(integer != 0) {
list.add(integer % 10);
integer = integer / 10;
}
Collections.reverse(list);
return list;
}
/**
* calucaltes the sum of all integers in array multiplied with
* their position.
*
* @return sum of all integers
*/
private int sum(){
int sum = 0;
for (int i = 0; this.list.size() > i; i++) {
sum += (i+1) * this.list.get(i);
}
return sum;
}
}
/**
* Main class
* Example usage of the ISBN class
*
* @author Tim Kächele
* @copyright Copyright (c) 2014 Tim Kächele
* @license MIT License
*/
public class Main {
public static void main(String[] args) {
Isbn isbn = new Isbn(900200902);
isbn.complete();
System.out.println(isbn);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment