diff options
Diffstat (limited to 'src/main/java/sevenUnits/unit')
-rw-r--r-- | src/main/java/sevenUnits/unit/UnitDatabase.java | 44 |
1 files changed, 13 insertions, 31 deletions
diff --git a/src/main/java/sevenUnits/unit/UnitDatabase.java b/src/main/java/sevenUnits/unit/UnitDatabase.java index ea0aa7f..7e76729 100644 --- a/src/main/java/sevenUnits/unit/UnitDatabase.java +++ b/src/main/java/sevenUnits/unit/UnitDatabase.java @@ -1,5 +1,5 @@ /** - * Copyright (C) 2018 Adrien Hopkins + * Copyright (C) 2018-2024 Adrien Hopkins * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -1274,7 +1274,11 @@ public final class UnitDatabase { private final ExpressionParser<ObjectProduct<BaseDimension>> unitDimensionParser = new ExpressionParser.Builder<>( this::getDimension).addBinaryOperator("*", (o1, o2) -> o1.times(o2), 0) .addSpaceFunction("*") - .addBinaryOperator("/", (o1, o2) -> o1.dividedBy(o2), 0).build(); + .addBinaryOperator("/", (o1, o2) -> o1.dividedBy(o2), 0) + .addNumericOperator("^", (o1, o2) -> { + int exponent = (int) Math.round(o2.value()); + return o1.toExponent(exponent); + }, 1).build(); /** * Creates the {@code UnitsDatabase}. @@ -1580,10 +1584,6 @@ public final class UnitDatabase { /** * Gets a unit dimension from the database using its name. * - * <p> - * This method accepts exponents, like "L^3" - * </p> - * * @param name dimension's name * @return dimension * @since 2019-03-14 @@ -1591,30 +1591,13 @@ public final class UnitDatabase { */ public ObjectProduct<BaseDimension> getDimension(final String name) { Objects.requireNonNull(name, "name must not be null."); - if (name.contains("^")) { - final String[] baseAndExponent = name.split("\\^"); - - final ObjectProduct<BaseDimension> base = this - .getDimension(baseAndExponent[0]); - - final int exponent; - try { - exponent = Integer - .parseInt(baseAndExponent[baseAndExponent.length - 1]); - } catch (final NumberFormatException e2) { - throw new IllegalArgumentException("Exponent must be an integer."); - } - - return base.toExponent(exponent); - } else { - final ObjectProduct<BaseDimension> dimension = this.dimensions - .get(name); - if (dimension == null) - throw new NoSuchElementException( - "No dimension with name \"" + name + "\"."); - else - return dimension; - } + final ObjectProduct<BaseDimension> dimension = this.dimensions + .get(name); + if (dimension == null) + throw new NoSuchElementException( + "No dimension with name \"" + name + "\"."); + else + return dimension; } /** @@ -1653,7 +1636,6 @@ public final class UnitDatabase { modifiedExpression = replacement.getKey().matcher(modifiedExpression) .replaceAll(replacement.getValue()); } - modifiedExpression = modifiedExpression.replaceAll(" *\\^ *", "\\^"); return this.unitDimensionParser.parseExpression(modifiedExpression); } |