lots of exercises in java... from https://github.com/exercism/java

12345678910111213141516171819202122232425262728293031323334
  1. public class Octal {
  2. private String octal;
  3. private int decimal;
  4. public Octal(String octal) {
  5. this.octal = octal;
  6. this.decimal = getDecimalFromOctal(octal);
  7. }
  8. public int getDecimal() {
  9. return decimal;
  10. }
  11. private static int getDecimalFromOctal(String octal) {
  12. if (!isValid(octal)) {
  13. return 0;
  14. }
  15. int sum = 0;
  16. for (int index = 0; index < octal.length(); index++) {
  17. sum += Character.getNumericValue(octal.charAt(index)) * Math.pow(8, octal.length() - index - 1);
  18. }
  19. return sum;
  20. }
  21. private static boolean isValid(String binaryRepresentation) {
  22. return binaryRepresentation.chars()
  23. .allMatch(x -> Character.isDigit((char) x) && Character.getNumericValue((char) x) < 8);
  24. }
  25. }