Skip to content

Instantly share code, notes, and snippets.

@aoetk
Created February 21, 2016 10:50
Show Gist options
  • Save aoetk/04ae349995f41f79adc8 to your computer and use it in GitHub Desktop.
Save aoetk/04ae349995f41f79adc8 to your computer and use it in GitHub Desktop.
チェックディジット (Modulus10 / Weight3) のサンプル
package aoetk;
public class CheckDigitApp {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java aoetk.CheckDigitApp target");
System.exit(1);
}
try {
System.out.println(getCheckDigit(args[0]));
} catch (NumberFormatException e) {
System.out.println("Argument is not a number.");
System.exit(1);
}
}
static String getCheckDigit(String target) throws NumberFormatException {
int sum = 0;
for (int i = 1; i <= target.length(); i++) {
String digitStr = target.substring(target.length() - i, target.length() - i + 1);
int digit = Integer.parseInt(digitStr);
if (i % 2 == 0) {
// 偶数位置は等倍
sum += digit;
} else {
// 奇数位置は3倍
sum += digit * 3;
}
}
int mod = sum % 10;
if (mod == 0) {
return Integer.toString(0);
} else {
return Integer.toString(10 - mod);
}
}
}
package aoetk;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class CheckDigitAppTest {
@Test
public void testGetCheckDigit_odd() throws Exception {
String target = "351386327796";
assertThat(CheckDigitApp.getCheckDigit(target), is("2"));
}
@Test
public void testGetCheckDigit_even() throws Exception {
String target = "51386327796";
assertThat(CheckDigitApp.getCheckDigit(target), is("5"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment