From da740edd3972fa049c4c8d0e43448c10a6a65dce Mon Sep 17 00:00:00 2001 From: Adrien Hopkins Date: Sun, 15 Jun 2025 19:26:12 -0500 Subject: Format & clean up source code --- src/main/java/sevenUnits/unit/BaseDimension.java | 14 +- src/main/java/sevenUnits/unit/BaseUnit.java | 16 +- src/main/java/sevenUnits/unit/BritishImperial.java | 14 +- src/main/java/sevenUnits/unit/FunctionalUnit.java | 14 +- src/main/java/sevenUnits/unit/LinearUnit.java | 141 +++--- src/main/java/sevenUnits/unit/LinearUnitValue.java | 96 ++-- .../java/sevenUnits/unit/LoadingException.java | 32 +- src/main/java/sevenUnits/unit/Metric.java | 12 +- src/main/java/sevenUnits/unit/USCustomary.java | 10 +- src/main/java/sevenUnits/unit/Unit.java | 61 ++- src/main/java/sevenUnits/unit/UnitDatabase.java | 496 ++++++++++----------- src/main/java/sevenUnits/unit/UnitPrefix.java | 88 ++-- src/main/java/sevenUnits/unit/UnitType.java | 5 +- src/main/java/sevenUnits/unit/UnitValue.java | 36 +- src/main/java/sevenUnits/unit/package-info.java | 2 +- 15 files changed, 485 insertions(+), 552 deletions(-) (limited to 'src/main/java/sevenUnits/unit') diff --git a/src/main/java/sevenUnits/unit/BaseDimension.java b/src/main/java/sevenUnits/unit/BaseDimension.java index fe7b772..11b822e 100644 --- a/src/main/java/sevenUnits/unit/BaseDimension.java +++ b/src/main/java/sevenUnits/unit/BaseDimension.java @@ -23,7 +23,7 @@ import sevenUnits.utils.Nameable; /** * A dimension that defines a {@code BaseUnit} - * + * * @author Adrien Hopkins * @since 2019-10-16 * @since v0.3.0 @@ -31,7 +31,7 @@ import sevenUnits.utils.Nameable; public final class BaseDimension implements Nameable { /** * Gets a {@code BaseDimension} with the provided name and symbol. - * + * * @param name name of dimension * @param symbol symbol used for dimension * @return dimension @@ -42,9 +42,7 @@ public final class BaseDimension implements Nameable { return new BaseDimension(name, symbol); } - /** - * The name of the dimension. - */ + /** The name of the dimension. */ private final String name; /** * The symbol used by the dimension. Symbols should be short, generally one @@ -54,7 +52,7 @@ public final class BaseDimension implements Nameable { /** * Creates the {@code BaseDimension}. - * + * * @param name name of unit * @param symbol symbol of unit * @throws NullPointerException if any argument is null @@ -66,9 +64,7 @@ public final class BaseDimension implements Nameable { this.symbol = Objects.requireNonNull(symbol, "symbol must not be null."); } - /** - * @since v0.4.0 - */ + /** @since v0.4.0 */ @Override public NameSymbol getNameSymbol() { return NameSymbol.of(this.name, this.symbol); diff --git a/src/main/java/sevenUnits/unit/BaseUnit.java b/src/main/java/sevenUnits/unit/BaseUnit.java index 2898de5..13e76d9 100644 --- a/src/main/java/sevenUnits/unit/BaseUnit.java +++ b/src/main/java/sevenUnits/unit/BaseUnit.java @@ -28,7 +28,7 @@ import sevenUnits.utils.NameSymbol; * Note that BaseUnits must have names and symbols. This is because they * are used for toString code. Therefore, the Optionals provided by * {@link #getPrimaryName} and {@link #getSymbol} will always contain a value. - * + * * @author Adrien Hopkins * @since 2019-10-16 * @since v0.3.0 @@ -36,7 +36,7 @@ import sevenUnits.utils.NameSymbol; public final class BaseUnit extends Unit { /** * Gets a base unit from the dimension it measures, its name and its symbol. - * + * * @param dimension dimension measured by this unit * @param name name of unit * @param symbol symbol of unit @@ -51,7 +51,7 @@ public final class BaseUnit extends Unit { /** * Gets a base unit from the dimension it measures, its name and its symbol. - * + * * @param dimension dimension measured by this unit * @param name name of unit * @param symbol symbol of unit @@ -65,14 +65,12 @@ public final class BaseUnit extends Unit { return new BaseUnit(dimension, name, symbol, otherNames); } - /** - * The dimension measured by this base unit. - */ + /** The dimension measured by this base unit. */ private final BaseDimension dimension; /** * Creates the {@code BaseUnit}. - * + * * @param dimension dimension of unit * @param primaryName name of unit * @param symbol symbol of unit @@ -91,7 +89,7 @@ public final class BaseUnit extends Unit { * Returns a {@code LinearUnit} with this unit as a base and a conversion * factor of 1. This operation must be done in order to allow units to be * created with operations. - * + * * @return this unit as a {@code LinearUnit} * @since 2019-10-16 * @since v0.3.0 @@ -115,7 +113,7 @@ public final class BaseUnit extends Unit { * @since 2019-10-16 * @since v0.3.0 */ - public final BaseDimension getBaseDimension() { + public BaseDimension getBaseDimension() { return this.dimension; } diff --git a/src/main/java/sevenUnits/unit/BritishImperial.java b/src/main/java/sevenUnits/unit/BritishImperial.java index a6fd43f..408e9e8 100644 --- a/src/main/java/sevenUnits/unit/BritishImperial.java +++ b/src/main/java/sevenUnits/unit/BritishImperial.java @@ -20,7 +20,7 @@ import sevenUnits.utils.NameSymbol; /** * A static utility class that contains units in the British Imperial system. - * + * * @author Adrien Hopkins * @since 2019-10-21 * @since v0.3.0 @@ -31,7 +31,7 @@ import sevenUnits.utils.NameSymbol; public final class BritishImperial { /** * Imperial units that measure area - * + * * @author Adrien Hopkins * @since 2019-11-08 * @since v0.3.0 @@ -47,7 +47,7 @@ public final class BritishImperial { /** * Imperial units that measure length - * + * * @author Adrien Hopkins * @since 2019-10-28 * @since v0.3.0 @@ -70,7 +70,9 @@ public final class BritishImperial { /** A league, equal to 3 miles. */ public static final LinearUnit LEAGUE = MILE.times(3); - /** A nautical mile, around 1 arcminute around the Earth's circumference. */ + /** + * A nautical mile, around 1 arcminute around the Earth's circumference. + */ public static final LinearUnit NAUTICAL_MILE = Metric.METRE.times(1852); public static final LinearUnit CABLE = NAUTICAL_MILE.dividedBy(10); public static final LinearUnit FATHOM = CABLE.dividedBy(100); @@ -81,7 +83,7 @@ public final class BritishImperial { /** * British Imperial units that measure mass. - * + * * @author Adrien Hopkins * @since 2019-11-08 * @since v0.3.0 @@ -100,7 +102,7 @@ public final class BritishImperial { /** * British Imperial units that measure volume - * + * * @author Adrien Hopkins * @since 2019-11-08 * @since v0.3.0 diff --git a/src/main/java/sevenUnits/unit/FunctionalUnit.java b/src/main/java/sevenUnits/unit/FunctionalUnit.java index 41db164..1d55b42 100644 --- a/src/main/java/sevenUnits/unit/FunctionalUnit.java +++ b/src/main/java/sevenUnits/unit/FunctionalUnit.java @@ -24,7 +24,7 @@ import sevenUnits.utils.ObjectProduct; /** * A unit that uses functional objects to convert to and from its base. - * + * * @author Adrien Hopkins * @since 2019-05-22 * @since v0.3.0 @@ -33,7 +33,7 @@ final class FunctionalUnit extends Unit { /** * A function that accepts a value expressed in the unit's base and returns * that value expressed in this unit. - * + * * @since 2019-05-22 * @since v0.3.0 */ @@ -42,7 +42,7 @@ final class FunctionalUnit extends Unit { /** * A function that accepts a value expressed in the unit and returns that * value expressed in the unit's base. - * + * * @since 2019-05-22 * @since v0.3.0 */ @@ -50,7 +50,7 @@ final class FunctionalUnit extends Unit { /** * Creates the {@code FunctionalUnit}. - * + * * @param base unit's base * @param converterFrom function that accepts a value expressed in the unit's * base and returns that value expressed in this unit. @@ -72,7 +72,7 @@ final class FunctionalUnit extends Unit { /** * Creates the {@code FunctionalUnit}. - * + * * @param base unit's base * @param converterFrom function that accepts a value expressed in the unit's * base and returns that value expressed in this unit. @@ -95,7 +95,7 @@ final class FunctionalUnit extends Unit { /** * {@inheritDoc} - * + * * Uses {@code converterFrom} to convert. */ @Override @@ -105,7 +105,7 @@ final class FunctionalUnit extends Unit { /** * {@inheritDoc} - * + * * Uses {@code converterTo} to convert. */ @Override diff --git a/src/main/java/sevenUnits/unit/LinearUnit.java b/src/main/java/sevenUnits/unit/LinearUnit.java index 7191196..22105b6 100644 --- a/src/main/java/sevenUnits/unit/LinearUnit.java +++ b/src/main/java/sevenUnits/unit/LinearUnit.java @@ -26,7 +26,7 @@ import sevenUnits.utils.UncertainDouble; /** * A unit that can be expressed as a product of its base and a number. For * example, kilometres, inches and pounds. - * + * * @author Adrien Hopkins * @since 2019-10-16 * @since v0.3.0 @@ -35,7 +35,7 @@ public final class LinearUnit extends Unit { /** * Gets a {@code LinearUnit} from a unit and a value. For example, converts * '59 °F' to a linear unit with the value of '288.15 K' - * + * * @param unit unit to convert * @param value value to convert * @return value expressed as a {@code LinearUnit} @@ -48,11 +48,11 @@ public final class LinearUnit extends Unit { Objects.requireNonNull(unit, "unit must not be null.").getBase(), unit.convertToBase(value), NameSymbol.EMPTY); } - + /** * Gets a {@code LinearUnit} from a unit and a value. For example, converts * '59 °F' to a linear unit with the value of '288.15 K' - * + * * @param unit unit to convert * @param value value to convert * @param ns name(s) and symbol of unit @@ -67,7 +67,7 @@ public final class LinearUnit extends Unit { Objects.requireNonNull(unit, "unit must not be null.").getBase(), unit.convertToBase(value), ns); } - + /** * @param unit unit to get base version of * @return the base unit associated with {@code unit}, as a @@ -78,12 +78,12 @@ public final class LinearUnit extends Unit { public static LinearUnit getBase(final Unit unit) { return new LinearUnit(unit.getBase(), 1, NameSymbol.EMPTY); } - + /** * Gets a {@code LinearUnit} from a unit base and a conversion factor. In * other words, gets the product of {@code unitBase} and * {@code conversionFactor}, expressed as a {@code LinearUnit}. - * + * * @param unitBase unit base to multiply by * @param conversionFactor number to multiply base by * @return product of base and conversion factor @@ -95,12 +95,12 @@ public final class LinearUnit extends Unit { final double conversionFactor) { return new LinearUnit(unitBase, conversionFactor, NameSymbol.EMPTY); } - + /** * Gets a {@code LinearUnit} from a unit base and a conversion factor. In * other words, gets the product of {@code unitBase} and * {@code conversionFactor}, expressed as a {@code LinearUnit}. - * + * * @param unitBase unit base to multiply by * @param conversionFactor number to multiply base by * @param ns name(s) and symbol of unit @@ -113,22 +113,22 @@ public final class LinearUnit extends Unit { final double conversionFactor, final NameSymbol ns) { return new LinearUnit(unitBase, conversionFactor, ns); } - + /** * The value of this unit as represented in its base form. Mathematically, - * + * *
 	 * this = conversionFactor * getBase()
 	 * 
- * + * * @since 2019-10-16 * @since v0.3.0 */ private final double conversionFactor; - + /** * Creates the {@code LinearUnit}. - * + * * @param unitBase base of linear unit * @param conversionFactor conversion factor between base and unit * @since 2019-10-16 @@ -139,21 +139,21 @@ public final class LinearUnit extends Unit { super(unitBase, ns); this.conversionFactor = conversionFactor; } - + /** * {@inheritDoc} - * + * * Converts by dividing by {@code conversionFactor} */ @Override protected double convertFromBase(final double value) { return value / this.getConversionFactor(); } - + /** * Converts an {@code UncertainDouble} value expressed in this unit to an * {@code UncertainValue} value expressed in {@code other}. - * + * * @param other unit to convert to * @param value value to convert * @return converted value @@ -170,35 +170,34 @@ public final class LinearUnit extends Unit { if (this.canConvertTo(other)) return value.timesExact( this.getConversionFactor() / other.getConversionFactor()); - else - throw new IllegalArgumentException( - String.format("Cannot convert from %s to %s.", this, other)); - + throw new IllegalArgumentException( + String.format("Cannot convert from %s to %s.", this, other)); + } - + /** * {@inheritDoc} - * + * * Converts by multiplying by {@code conversionFactor} */ @Override protected double convertToBase(final double value) { return value * this.getConversionFactor(); } - + /** * Converts an {@code UncertainDouble} to the base unit. - * + * * @since 2020-09-07 * @since v0.3.0 */ UncertainDouble convertToBase(final UncertainDouble value) { return value.timesExact(this.getConversionFactor()); } - + /** * Divides this unit by a scalar. - * + * * @param divisor scalar to divide by * @return quotient * @since 2018-12-23 @@ -207,10 +206,10 @@ public final class LinearUnit extends Unit { public LinearUnit dividedBy(final double divisor) { return valueOf(this.getBase(), this.getConversionFactor() / divisor); } - + /** * Returns the quotient of this unit and another. - * + * * @param divisor unit to divide by * @return quotient of two units * @throws NullPointerException if {@code divisor} is null @@ -219,24 +218,24 @@ public final class LinearUnit extends Unit { */ public LinearUnit dividedBy(final LinearUnit divisor) { Objects.requireNonNull(divisor, "other must not be null"); - + // divide the units - final ObjectProduct base = this.getBase() + final var base = this.getBase() .dividedBy(divisor.getBase()); return valueOf(base, this.getConversionFactor() / divisor.getConversionFactor()); } - + /** * {@inheritDoc} - * + * * Uses the base and conversion factor of units to test for equality. */ @Override public boolean equals(final Object obj) { if (!(obj instanceof LinearUnit)) return false; - final LinearUnit other = (LinearUnit) obj; + final var other = (LinearUnit) obj; return Objects.equals(this.getBase(), other.getBase()) && Double.compare(this.getConversionFactor(), other.getConversionFactor()) == 0; @@ -244,18 +243,18 @@ public final class LinearUnit extends Unit { /** * @param other unit to test equality with - * @return true iff this unit and other are equal, - * ignoring small differences caused by floating-point error. - * - * @apiNote This method is not transitive, - * so it cannot be used as an equals method. + * @return true iff this unit and other are equal, ignoring small differences + * caused by floating-point error. + * + * @apiNote This method is not transitive, so it cannot be used as an equals + * method. */ public boolean equalsApproximately(final LinearUnit other) { return Objects.equals(this.getBase(), other.getBase()) && DecimalComparison.equals(this.getConversionFactor(), other.getConversionFactor()); } - + /** * @return conversion factor * @since 2019-10-16 @@ -264,10 +263,10 @@ public final class LinearUnit extends Unit { public double getConversionFactor() { return this.conversionFactor; } - + /** * {@inheritDoc} - * + * * Uses the base and conversion factor to compute a hash code. */ @Override @@ -275,7 +274,7 @@ public final class LinearUnit extends Unit { return 31 * this.getBase().hashCode() + Double.hashCode(this.getConversionFactor()); } - + /** * @return whether this unit is equivalent to a {@code BaseUnit} (i.e. there * is a {@code BaseUnit b} where @@ -286,7 +285,7 @@ public final class LinearUnit extends Unit { public boolean isBase() { return this.isCoherent() && this.getBase().isSingleObject(); } - + /** * @return whether this unit is coherent (i.e. has conversion factor 1) * @since 2019-10-16 @@ -295,7 +294,7 @@ public final class LinearUnit extends Unit { public boolean isCoherent() { return this.getConversionFactor() == 1; } - + /** * Returns the difference of this unit and another. *

@@ -304,7 +303,7 @@ public final class LinearUnit extends Unit { * does not meet this condition, an {@code IllegalArgumentException} will be * thrown. *

- * + * * @param subtrahend unit to subtract * @return difference of units * @throws IllegalArgumentException if {@code subtrahend} is not compatible @@ -315,18 +314,18 @@ public final class LinearUnit extends Unit { */ public LinearUnit minus(final LinearUnit subtrahend) { Objects.requireNonNull(subtrahend, "addend must not be null."); - + // reject subtrahends that cannot be added to this unit if (!this.getBase().equals(subtrahend.getBase())) throw new IllegalArgumentException(String.format( "Incompatible units for subtraction \"%s\" and \"%s\".", this, subtrahend)); - + // subtract the units return valueOf(this.getBase(), this.getConversionFactor() - subtrahend.getConversionFactor()); } - + /** * Returns the sum of this unit and another. *

@@ -335,7 +334,7 @@ public final class LinearUnit extends Unit { * does not meet this condition, an {@code IllegalArgumentException} will be * thrown. *

- * + * * @param addend unit to add * @return sum of units * @throws IllegalArgumentException if {@code addend} is not compatible for @@ -346,21 +345,21 @@ public final class LinearUnit extends Unit { */ public LinearUnit plus(final LinearUnit addend) { Objects.requireNonNull(addend, "addend must not be null."); - + // reject addends that cannot be added to this unit if (!this.getBase().equals(addend.getBase())) throw new IllegalArgumentException(String.format( "Incompatible units for addition \"%s\" and \"%s\".", this, addend)); - + // add the units return valueOf(this.getBase(), this.getConversionFactor() + addend.getConversionFactor()); } - + /** * Multiplies this unit by a scalar. - * + * * @param multiplier scalar to multiply by * @return product * @since 2018-12-23 @@ -369,10 +368,10 @@ public final class LinearUnit extends Unit { public LinearUnit times(final double multiplier) { return valueOf(this.getBase(), this.getConversionFactor() * multiplier); } - + /** * Returns the product of this unit and another. - * + * * @param multiplier unit to multiply by * @return product of two units * @throws NullPointerException if {@code multiplier} is null @@ -381,24 +380,24 @@ public final class LinearUnit extends Unit { */ public LinearUnit times(final LinearUnit multiplier) { Objects.requireNonNull(multiplier, "other must not be null"); - + // multiply the units - final ObjectProduct base = this.getBase() + final var base = this.getBase() .times(multiplier.getBase()); return valueOf(base, this.getConversionFactor() * multiplier.getConversionFactor()); } - + @Override public String toDefinitionString() { return Double.toString(this.conversionFactor) + (this.getBase().equals(ObjectProduct.empty()) ? "" : " " + this.getBase().toString(BaseUnit::getShortName)); } - + /** * Returns this unit but to an exponent. - * + * * @param exponent exponent to exponentiate unit to * @return exponentiated unit * @since 2019-01-15 @@ -408,11 +407,11 @@ public final class LinearUnit extends Unit { return valueOf(this.getBase().toExponent(exponent), Math.pow(this.conversionFactor, exponent)); } - + /** * Returns this unit to an exponent, rounding the resulting dimensions to the * nearest integer. - * + * * @param exponent exponent to raise unit to * @return result of rounded exponentation * @since 2024-08-22 @@ -423,12 +422,12 @@ public final class LinearUnit extends Unit { return valueOf(this.getBase().toExponentRounded(exponent), Math.pow(this.conversionFactor, exponent)); } - + @Override public LinearUnit withName(final NameSymbol ns) { return valueOf(this.getBase(), this.getConversionFactor(), ns); } - + /** * Returns the result of applying {@code prefix} to this unit. *

@@ -438,7 +437,7 @@ public final class LinearUnit extends Unit { * have a symbol.
* This method ignores alternate names of both this unit and the provided * prefix. - * + * * @param prefix prefix to apply * @return unit with prefix * @since 2019-03-18 @@ -446,8 +445,8 @@ public final class LinearUnit extends Unit { * @throws NullPointerException if prefix is null */ public LinearUnit withPrefix(final UnitPrefix prefix) { - final LinearUnit unit = this.times(prefix.getMultiplier()); - + final var unit = this.times(prefix.getMultiplier()); + // create new name and symbol, if possible final String name; if (this.getPrimaryName().isPresent() @@ -456,14 +455,14 @@ public final class LinearUnit extends Unit { } else { name = null; } - + final String symbol; if (this.getSymbol().isPresent() && prefix.getSymbol().isPresent()) { symbol = prefix.getSymbol().get() + this.getSymbol().get(); } else { symbol = null; } - + return unit.withName(NameSymbol.ofNullable(name, symbol)); } } diff --git a/src/main/java/sevenUnits/unit/LinearUnitValue.java b/src/main/java/sevenUnits/unit/LinearUnitValue.java index 86520d7..9a99e00 100644 --- a/src/main/java/sevenUnits/unit/LinearUnitValue.java +++ b/src/main/java/sevenUnits/unit/LinearUnitValue.java @@ -20,7 +20,6 @@ import java.math.RoundingMode; import java.util.ArrayList; import java.util.List; import java.util.Objects; -import java.util.Optional; import sevenUnits.utils.DecimalComparison; import sevenUnits.utils.ObjectProduct; @@ -28,10 +27,10 @@ import sevenUnits.utils.UncertainDouble; /** * A possibly uncertain value expressed in a linear unit. - * + * * Unless otherwise indicated, all methods in this class throw a * {@code NullPointerException} when an argument is null. - * + * * @author Adrien Hopkins * @since 2020-07-26 * @since v0.3.0 @@ -42,14 +41,14 @@ public final class LinearUnitValue { /** * Gets an exact {@code LinearUnitValue} - * + * * @param unit unit to express with * @param value value to express * @return exact {@code LinearUnitValue} instance * @since 2020-07-26 * @since v0.3.0 */ - public static final LinearUnitValue getExact(final LinearUnit unit, + public static LinearUnitValue getExact(final LinearUnit unit, final double value) { return new LinearUnitValue( Objects.requireNonNull(unit, "unit must not be null"), @@ -58,14 +57,14 @@ public final class LinearUnitValue { /** * Gets an uncertain {@code LinearUnitValue} - * + * * @param unit unit to express with * @param value value to express * @return uncertain {@code LinearUnitValue} instance * @since 2020-07-26 * @since v0.3.0 */ - public static final LinearUnitValue of(final LinearUnit unit, + public static LinearUnitValue of(final LinearUnit unit, final UncertainDouble value) { return new LinearUnitValue( Objects.requireNonNull(unit, "unit must not be null"), @@ -93,7 +92,7 @@ public final class LinearUnitValue { * @since 2020-08-04 * @since v0.3.0 */ - public final UnitValue asUnitValue() { + public UnitValue asUnitValue() { return UnitValue.of(this.unit, this.value.value()); } @@ -103,20 +102,20 @@ public final class LinearUnitValue { * @since 2020-07-26 * @since v0.3.0 */ - public final boolean canConvertTo(final LinearUnit other) { + public boolean canConvertTo(final LinearUnit other) { return this.unit.canConvertTo(other); } /** * Returns a LinearUnitValue that represents the same value expressed in a * different unit - * + * * @param other new unit to express value in * @return value expressed in {@code other} * @since 2020-07-26 * @since v0.3.0 */ - public final LinearUnitValue convertTo(final LinearUnit other) { + public LinearUnitValue convertTo(final LinearUnit other) { return LinearUnitValue.of(other, this.unit.convertTo(other, this.value)); } @@ -131,7 +130,7 @@ public final class LinearUnitValue { * @since 2024-08-15 * @since v1.0.0 */ - public final List convertToMultiple( + public List convertToMultiple( final List others) { if (others.size() < 1) throw new IllegalArgumentException("Must have at least one unit"); @@ -141,17 +140,17 @@ public final class LinearUnitValue { "All provided units must have the same base as the value."); } - LinearUnitValue remaining = this; + var remaining = this; final List values = new ArrayList<>(others.size()); for (final LinearUnit unit : others.subList(0, others.size() - 1)) { - final LinearUnitValue remainingInUnit = remaining.convertTo(unit); - final LinearUnitValue value = getExact(unit, + final var remainingInUnit = remaining.convertTo(unit); + final var value = getExact(unit, Math.floor(remainingInUnit.getValueExact() + 1e-12)); values.add(value); remaining = remaining.minus(value); } - final LinearUnitValue lastValue = remaining + final var lastValue = remaining .convertTo(others.get(others.size() - 1)); values.add(lastValue); return values; @@ -159,7 +158,7 @@ public final class LinearUnitValue { /** * Divides this value by a scalar - * + * * @param divisor value to divide by * @return multiplied value * @since 2020-07-28 @@ -171,7 +170,7 @@ public final class LinearUnitValue { /** * Divides this value by another value - * + * * @param divisor value to multiply by * @return quotient * @since 2020-07-28 @@ -186,7 +185,7 @@ public final class LinearUnitValue { * Returns true if this and obj represent the same value, regardless of * whether or not they are expressed in the same unit. So (1000 m).equals(1 * km) returns true. - * + * * @since 2020-07-26 * @since v0.3.0 * @see #equals(Object, boolean) @@ -195,7 +194,7 @@ public final class LinearUnitValue { public boolean equals(final Object obj) { if (!(obj instanceof LinearUnitValue)) return false; - final LinearUnitValue other = (LinearUnitValue) obj; + final var other = (LinearUnitValue) obj; return Objects.equals(this.unit.getBase(), other.unit.getBase()) && this.unit.convertToBase(this.value) .equals(other.unit.convertToBase(other.value)); @@ -205,13 +204,13 @@ public final class LinearUnitValue { * Returns true if this and obj represent the same value, regardless of * whether or not they are expressed in the same unit. So (1000 m).equals(1 * km) returns true. - * + * * @param obj object to test equality with * @param avoidFPErrors if true, this method will attempt to avoid * floating-point errors, at the cost of not always * being transitive. * @return true iff this and obj are equal - * + * * @since 2020-07-28 * @since v0.3.0 */ @@ -220,7 +219,7 @@ public final class LinearUnitValue { return this.equals(obj); if (!(obj instanceof LinearUnitValue)) return false; - final LinearUnitValue other = (LinearUnitValue) obj; + final var other = (LinearUnitValue) obj; return Objects.equals(this.unit.getBase(), other.unit.getBase()) && DecimalComparison.equals(this.unit.convertToBase(this.value), other.unit.convertToBase(other.value)); @@ -229,7 +228,7 @@ public final class LinearUnitValue { /** * @param other another {@code LinearUnitValue} * @return true iff this and other are within each other's uncertainty range - * + * * @since 2020-07-26 * @since v0.3.0 */ @@ -237,9 +236,9 @@ public final class LinearUnitValue { if (other == null || !Objects.equals(this.unit.getBase(), other.unit.getBase())) return false; - final LinearUnit base = LinearUnit.valueOf(this.unit.getBase(), 1); - final LinearUnitValue thisBase = this.convertTo(base); - final LinearUnitValue otherBase = other.convertTo(base); + final var base = LinearUnit.valueOf(this.unit.getBase(), 1); + final var thisBase = this.convertTo(base); + final var otherBase = other.convertTo(base); return thisBase.value.equivalent(otherBase.value); } @@ -249,7 +248,7 @@ public final class LinearUnitValue { * @since 2020-09-29 * @since v0.3.0 */ - public final LinearUnit getUnit() { + public LinearUnit getUnit() { return this.unit; } @@ -258,7 +257,7 @@ public final class LinearUnitValue { * @since 2020-09-29 * @since v0.3.0 */ - public final UncertainDouble getValue() { + public UncertainDouble getValue() { return this.value; } @@ -267,7 +266,7 @@ public final class LinearUnitValue { * @since 2020-09-07 * @since v0.3.0 */ - public final double getValueExact() { + public double getValueExact() { return this.value.value(); } @@ -280,7 +279,7 @@ public final class LinearUnitValue { /** * Returns the difference of this value and another, expressed in this * value's unit - * + * * @param subtrahend value to subtract * @return difference of values * @throws IllegalArgumentException if {@code subtrahend} has a unit that is @@ -296,14 +295,14 @@ public final class LinearUnitValue { "Incompatible units for subtraction \"%s\" and \"%s\".", this.unit, subtrahend.unit)); - final LinearUnitValue otherConverted = subtrahend.convertTo(this.unit); + final var otherConverted = subtrahend.convertTo(this.unit); return LinearUnitValue.of(this.unit, this.value.minus(otherConverted.value)); } /** * Returns the sum of this value and another, expressed in this value's unit - * + * * @param addend value to add * @return sum of values * @throws IllegalArgumentException if {@code addend} has a unit that is not @@ -319,14 +318,14 @@ public final class LinearUnitValue { "Incompatible units for addition \"%s\" and \"%s\".", this.unit, addend.unit)); - final LinearUnitValue otherConverted = addend.convertTo(this.unit); + final var otherConverted = addend.convertTo(this.unit); return LinearUnitValue.of(this.unit, this.value.plus(otherConverted.value)); } /** * Multiplies this value by a scalar - * + * * @param multiplier value to multiply by * @return multiplied value * @since 2020-07-28 @@ -338,7 +337,7 @@ public final class LinearUnitValue { /** * Multiplies this value by another value - * + * * @param multiplier value to multiply by * @return product * @since 2020-07-28 @@ -351,7 +350,7 @@ public final class LinearUnitValue { /** * Raises a value to an exponent - * + * * @param exponent exponent to raise to * @return result of exponentiation * @since 2020-07-28 @@ -364,7 +363,7 @@ public final class LinearUnitValue { /** * Raises this value to an exponent, rounding all dimensions to integers. - * + * * @param exponent exponent to raise this value to * @return result of exponentation * @@ -391,28 +390,28 @@ public final class LinearUnitValue { * single numbers. *

* Non-exact values are rounded intelligently based on their uncertainty. - * + * * @param showUncertainty whether to show the value's uncertainty - * @param roundingMode how to round numbers in this string + * @param roundingMode how to round numbers in this string * @return string representing this value - * + * * @since 2020-07-26 * @since v0.3.0 */ public String toString(final boolean showUncertainty, RoundingMode roundingMode) { - final Optional primaryName = this.unit.getPrimaryName(); - final Optional symbol = this.unit.getSymbol(); - final String chosenName = symbol.orElse(primaryName.orElse(null)); + final var primaryName = this.unit.getPrimaryName(); + final var symbol = this.unit.getSymbol(); + final var chosenName = symbol.orElse(primaryName.orElse(null)); - final UncertainDouble baseValue = this.unit.convertToBase(this.value); + final var baseValue = this.unit.convertToBase(this.value); // get rounded strings // if showUncertainty is true, add brackets around the string - final String valueString = (showUncertainty ? "(" : "") + final var valueString = (showUncertainty ? "(" : "") + this.value.toString(showUncertainty, roundingMode) + (showUncertainty ? ")" : ""); - final String baseValueString = (showUncertainty ? "(" : "") + final var baseValueString = (showUncertainty ? "(" : "") + baseValue.toString(showUncertainty, roundingMode) + (showUncertainty ? ")" : ""); @@ -421,7 +420,6 @@ public final class LinearUnitValue { return String.format("%s unnamed unit (= %s %s)", valueString, baseValueString, this.unit.getBase() .toString(unit -> unit.getSymbol().orElseThrow())); - else - return String.format("%s %s", valueString, chosenName); + return String.format("%s %s", valueString, chosenName); } } diff --git a/src/main/java/sevenUnits/unit/LoadingException.java b/src/main/java/sevenUnits/unit/LoadingException.java index 7b3d708..2a75c99 100644 --- a/src/main/java/sevenUnits/unit/LoadingException.java +++ b/src/main/java/sevenUnits/unit/LoadingException.java @@ -22,15 +22,17 @@ import java.util.Optional; /** * An exception that occurred when loading a file. This wrapper class adds more * info about the error. - * + * * @author Adrien Hopkins * @since 2024-08-22 * @since v1.0.0 */ public final class LoadingException extends RuntimeException { /** The type of file that was being loaded. */ - public static enum FileType { - @SuppressWarnings("javadoc") UNIT, @SuppressWarnings("javadoc") DIMENSION + public enum FileType { + @SuppressWarnings("javadoc") + UNIT, @SuppressWarnings("javadoc") + DIMENSION } private static final long serialVersionUID = -8167971828216907607L; @@ -45,7 +47,7 @@ public final class LoadingException extends RuntimeException { /** * Create a LoadingException from some information, without a file. - * + * * @param lineNumber line number error happened on * @param line text of invalid line * @param fileType type of file @@ -63,7 +65,7 @@ public final class LoadingException extends RuntimeException { /** * Create a LoadingException from some information, with a file. - * + * * @param lineNumber line number error happened on * @param line text of invalid line * @param file file error happened on @@ -80,16 +82,12 @@ public final class LoadingException extends RuntimeException { this.problem = problem; } - /** - * @return the file this error happened in, if there is one - */ + /** @return the file this error happened in, if there is one */ public Optional file() { return this.file; } - /** - * @return type of file that this error happened in - */ + /** @return type of file that this error happened in */ public FileType fileType() { return this.fileType; } @@ -107,23 +105,17 @@ public final class LoadingException extends RuntimeException { this.line, this.problem)); } - /** - * @return text of line that caused this error - */ + /** @return text of line that caused this error */ public String line() { return this.line; } - /** - * @return number of line that caused this error - */ + /** @return number of line that caused this error */ public long lineNumber() { return this.lineNumber; } - /** - * @return the error, as an exception - */ + /** @return the error, as an exception */ public RuntimeException problem() { return this.problem; } diff --git a/src/main/java/sevenUnits/unit/Metric.java b/src/main/java/sevenUnits/unit/Metric.java index 34fd0b8..e712dc3 100644 --- a/src/main/java/sevenUnits/unit/Metric.java +++ b/src/main/java/sevenUnits/unit/Metric.java @@ -24,16 +24,16 @@ import sevenUnits.utils.ObjectProduct; /** * All of the units, prefixes and dimensions that are used by the SI, as well as * some outside the SI. - * + * *

* This class does not include prefixed units. To obtain prefixed units, use * {@link LinearUnit#withPrefix}: - * + * *

  * LinearUnit KILOMETRE = SI.METRE.withPrefix(SI.KILO);
  * 
- * - * + * + * * @author Adrien Hopkins * @since 2019-10-16 * @since v0.3.0 @@ -107,7 +107,7 @@ public final class Metric { /** * Constants that relate to the SI or other systems. - * + * * @author Adrien Hopkins * @since 2019-11-08 * @since v0.3.0 @@ -350,7 +350,7 @@ public final class Metric { pr -> 0.5 * Math.log(pr), Np -> Math.exp(2 * Np)) .withName(NameSymbol.of("neper", "Np")); public static final Unit BEL = Unit.fromConversionFunctions(ONE.getBase(), - pr -> Math.log10(pr), dB -> Math.pow(10, dB)) + Math::log10, dB -> Math.pow(10, dB)) .withName(NameSymbol.of("bel", "B")); public static final Unit DECIBEL = Unit .fromConversionFunctions(ONE.getBase(), pr -> 10 * Math.log10(pr), diff --git a/src/main/java/sevenUnits/unit/USCustomary.java b/src/main/java/sevenUnits/unit/USCustomary.java index be8c5e2..ef12043 100644 --- a/src/main/java/sevenUnits/unit/USCustomary.java +++ b/src/main/java/sevenUnits/unit/USCustomary.java @@ -18,7 +18,7 @@ package sevenUnits.unit; /** * A static utility class that contains units in the US Customary system. - * + * * @author Adrien Hopkins * @since 2019-10-21 * @since v0.3.0 @@ -29,7 +29,7 @@ package sevenUnits.unit; public final class USCustomary { /** * US Customary units that measure area - * + * * @author Adrien Hopkins * @since 2019-11-08 * @since v0.3.0 @@ -48,7 +48,7 @@ public final class USCustomary { /** * US Customary units that measure length - * + * * @author Adrien Hopkins * @since 2019-10-28 * @since v0.3.0 @@ -79,7 +79,7 @@ public final class USCustomary { /** * mass units - * + * * @author Adrien Hopkins * @since 2019-11-08 * @since v0.3.0 @@ -100,7 +100,7 @@ public final class USCustomary { /** * Volume units - * + * * @author Adrien Hopkins * @since 2019-11-08 * @since v0.3.0 diff --git a/src/main/java/sevenUnits/unit/Unit.java b/src/main/java/sevenUnits/unit/Unit.java index d651fe2..40e6e0d 100644 --- a/src/main/java/sevenUnits/unit/Unit.java +++ b/src/main/java/sevenUnits/unit/Unit.java @@ -28,7 +28,7 @@ import sevenUnits.utils.ObjectProduct; /** * A unit that is composed of base units. - * + * * @author Adrien Hopkins * @since 2019-10-16 * @since v0.3.0 @@ -37,14 +37,14 @@ public abstract class Unit implements Nameable { /** * Returns a unit from its base and the functions it uses to convert to and * from its base. - * + * *

* For example, to get a unit representing the degree Celsius, the following * code can be used: - * + * * {@code Unit.fromConversionFunctions(SI.KELVIN, tempK -> tempK - 273.15, tempC -> tempC + 273.15);} *

- * + * * @param base unit's base * @param converterFrom function that accepts a value expressed in the unit's * base and returns that value expressed in this unit. @@ -65,14 +65,14 @@ public abstract class Unit implements Nameable { /** * Returns a unit from its base and the functions it uses to convert to and * from its base. - * + * *

* For example, to get a unit representing the degree Celsius, the following * code can be used: - * + * * {@code Unit.fromConversionFunctions(SI.KELVIN, tempK -> tempK - 273.15, tempC -> tempC + 273.15);} *

- * + * * @param base unit's base * @param converterFrom function that accepts a value expressed in the unit's * base and returns that value expressed in this unit. @@ -93,7 +93,7 @@ public abstract class Unit implements Nameable { /** * The combination of units that this unit is based on. - * + * * @since 2019-10-16 * @since v0.3.0 */ @@ -101,7 +101,7 @@ public abstract class Unit implements Nameable { /** * This unit's name(s) and symbol - * + * * @since 2020-09-07 * @since v0.3.0 */ @@ -117,21 +117,20 @@ public abstract class Unit implements Nameable { /** * A constructor that constructs {@code BaseUnit} instances. - * + * * @since 2019-10-16 * @since v0.3.0 */ Unit(final NameSymbol nameSymbol) { - if (this instanceof BaseUnit) { - this.unitBase = ObjectProduct.oneOf((BaseUnit) this); - } else + if (!(this instanceof BaseUnit)) throw new AssertionError(); + this.unitBase = ObjectProduct.oneOf((BaseUnit) this); this.nameSymbol = nameSymbol; } /** * Creates the {@code Unit}. - * + * * @param unitBase base of unit * @param ns names and symbol of unit * @since 2019-10-16 @@ -147,7 +146,7 @@ public abstract class Unit implements Nameable { /** * Checks if a value expressed in this unit can be converted to a value * expressed in {@code other} - * + * * @param other unit or unitlike form to test with * @return true if they are compatible * @since 2019-01-13 @@ -171,10 +170,10 @@ public abstract class Unit implements Nameable { * If this unit is a base unit, this method should return * {@code value}. *

- * + * * @implSpec This method is used by {@link #convertTo}, and its behaviour * affects the behaviour of {@code convertTo}. - * + * * @param value value expressed in base unit * @return value expressed in this unit * @since 2018-12-22 @@ -185,12 +184,12 @@ public abstract class Unit implements Nameable { /** * Converts a value expressed in this unit to a value expressed in * {@code other}. - * + * * @implSpec If unit conversion is possible, this implementation returns * {@code other.convertFromBase(this.convertToBase(value))}. * Therefore, overriding either of those methods will change the * output of this method. - * + * * @param other unit to convert to * @param value value to convert * @return converted value @@ -205,9 +204,8 @@ public abstract class Unit implements Nameable { Objects.requireNonNull(other, "other must not be null."); if (this.canConvertTo(other)) return other.convertFromBase(this.convertToBase(value)); - else - throw new IllegalArgumentException( - String.format("Cannot convert from %s to %s.", this, other)); + throw new IllegalArgumentException( + String.format("Cannot convert from %s to %s.", this, other)); } /** @@ -222,10 +220,10 @@ public abstract class Unit implements Nameable { * If this unit is a base unit, this method should return * {@code value}. *

- * + * * @implSpec This method is used by {@link #convertTo}, and its behaviour * affects the behaviour of {@code convertTo}. - * + * * @param value value expressed in this unit * @return value expressed in base unit * @since 2018-12-22 @@ -249,7 +247,7 @@ public abstract class Unit implements Nameable { */ public final ObjectProduct getDimension() { if (this.dimension == null) { - final Map mapping = this.unitBase.exponentMap(); + final var mapping = this.unitBase.exponentMap(); final Map dimensionMap = new HashMap<>(); for (final BaseUnit key : mapping.keySet()) { @@ -287,9 +285,9 @@ public abstract class Unit implements Nameable { *

* All SI units (as designated by the BIPM) except the degree Celsius are * considered "metric" by this definition. - * + * * @return true iff this unit is metric. - * + * * @since 2020-08-27 * @since v0.3.0 */ @@ -297,7 +295,7 @@ public abstract class Unit implements Nameable { // first condition - check that it is a linear unit if (!(this instanceof LinearUnit)) return false; - final LinearUnit linear = (LinearUnit) this; + final var linear = (LinearUnit) this; // second condition - check that for (final BaseUnit b : linear.getBase().getBaseSet()) { @@ -318,9 +316,7 @@ public abstract class Unit implements Nameable { public String toDefinitionString() { if (!this.unitBase.getNameSymbol().isEmpty()) return "derived from " + this.unitBase.getName(); - else - return "derived from " - + this.getBase().toString(BaseUnit::getShortName); + return "derived from " + this.getBase().toString(BaseUnit::getShortName); } /** @@ -338,8 +334,7 @@ public abstract class Unit implements Nameable { && this.nameSymbol.getSymbol().isPresent()) return this.nameSymbol.getPrimaryName().orElseThrow() + " (" + this.nameSymbol.getSymbol().orElseThrow() + ")"; - else - return this.getName(); + return this.getName(); } /** diff --git a/src/main/java/sevenUnits/unit/UnitDatabase.java b/src/main/java/sevenUnits/unit/UnitDatabase.java index a85ec5f..05e9cc9 100644 --- a/src/main/java/sevenUnits/unit/UnitDatabase.java +++ b/src/main/java/sevenUnits/unit/UnitDatabase.java @@ -40,7 +40,6 @@ import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; -import java.util.regex.Matcher; import java.util.regex.Pattern; import sevenUnits.utils.ConditionalExistenceCollections; @@ -51,7 +50,7 @@ import sevenUnits.utils.UncertainDouble; /** * A database of units, prefixes and dimensions, and their names. - * + * * @author Adrien Hopkins * @since 2019-01-07 * @since v0.1.0 @@ -88,7 +87,7 @@ public final class UnitDatabase { * Because of ambiguities between prefixes (i.e. kilokilo = mega), * {@link #containsValue} and {@link #values()} currently ignore prefixes. *

- * + * * @author Adrien Hopkins * @since 2019-04-13 * @since v0.2.0 @@ -96,7 +95,7 @@ public final class UnitDatabase { private static final class PrefixedUnitMap implements Map { /** * The class used for entry sets. - * + * *

* If the map that created this set is infinite in size (has at least one * unit and at least one prefix), this set is infinite as well. If this @@ -104,7 +103,7 @@ public final class UnitDatabase { * {@code IllegalStateException} instead of creating an infinite-sized * array. *

- * + * * @author Adrien Hopkins * @since 2019-04-13 * @since v0.2.0 @@ -113,7 +112,7 @@ public final class UnitDatabase { extends AbstractSet> { /** * The entry for this set. - * + * * @author Adrien Hopkins * @since 2019-04-14 * @since v0.2.0 @@ -125,7 +124,7 @@ public final class UnitDatabase { /** * Creates the {@code PrefixedUnitEntry}. - * + * * @param key key * @param value value * @since 2019-04-14 @@ -181,7 +180,7 @@ public final class UnitDatabase { * string is the string representation of the key, then the equals * ({@code =}) character, then the string representation of the * value. - * + * * @since 2019-05-03 * @since v0.3.0 */ @@ -194,7 +193,7 @@ public final class UnitDatabase { /** * An iterator that iterates over the units of a * {@code PrefixedUnitNameSet}. - * + * * @author Adrien Hopkins * @since 2019-04-14 * @since v0.2.0 @@ -214,9 +213,9 @@ public final class UnitDatabase { /** * Creates the * {@code UnitsDatabase.PrefixedUnitMap.PrefixedUnitNameSet.PrefixedUnitNameIterator}. - * + * * @param map map to base iterator on - * + * * @since 2019-04-14 * @since v0.2.0 */ @@ -232,7 +231,7 @@ public final class UnitDatabase { * @since v0.2.0 */ private String getCurrentUnitName() { - final StringBuilder unitName = new StringBuilder(); + final var unitName = new StringBuilder(); for (final int i : this.prefixCoordinates) { unitName.append(this.prefixNames.get(i)); } @@ -245,18 +244,15 @@ public final class UnitDatabase { public boolean hasNext() { if (this.unitNames.isEmpty()) return false; - else { - if (this.prefixNames.isEmpty()) - return this.prefixCoordinates.isEmpty() - && this.unitNamePosition < this.unitNames.size(); - else - return true; - } + if (this.prefixNames.isEmpty()) + return this.prefixCoordinates.isEmpty() + && this.unitNamePosition < this.unitNames.size(); + return true; } /** * Changes this iterator's position to the next available one. - * + * * @since 2019-04-14 * @since v0.2.0 */ @@ -272,7 +268,7 @@ public final class UnitDatabase { this.prefixCoordinates.add(0, 0); } else { // get the prefix coordinate to increment, then increment - int i = this.prefixCoordinates.size() - 1; + var i = this.prefixCoordinates.size() - 1; this.prefixCoordinates.set(i, this.prefixCoordinates.get(i) + 1); @@ -298,7 +294,7 @@ public final class UnitDatabase { @Override public Entry next() { // get next element - final Entry nextEntry = this.peek(); + final var nextEntry = this.peek(); // iterate to next position this.incrementPosition(); @@ -327,7 +323,7 @@ public final class UnitDatabase { } } - final String nextName = this.getCurrentUnitName(); + final var nextName = this.getCurrentUnitName(); return new PrefixedUnitEntry(nextName, this.map.get(nextName)); } @@ -335,7 +331,7 @@ public final class UnitDatabase { /** * Returns a string representation of the object. The exact details * of the representation are unspecified and subject to change. - * + * * @since 2019-05-03 * @since v0.3.0 */ @@ -352,7 +348,7 @@ public final class UnitDatabase { /** * Creates the {@code PrefixedUnitNameSet}. - * + * * @param map map that created this set * @since 2019-04-13 * @since v0.2.0 @@ -389,7 +385,7 @@ public final class UnitDatabase { // This is OK because I'm in a try-catch block, catching the // exact exception that would be thrown. @SuppressWarnings("unchecked") - final Entry tempEntry = (Entry) o; + final var tempEntry = (Entry) o; entry = tempEntry; } catch (final ClassCastException e) { throw new IllegalArgumentException( @@ -447,55 +443,45 @@ public final class UnitDatabase { public int size() { if (this.map.units.isEmpty()) return 0; - else { - if (this.map.prefixes.isEmpty()) - return this.map.units.size(); - else - // infinite set - return Integer.MAX_VALUE; - } + if (this.map.prefixes.isEmpty()) + return this.map.units.size(); + // infinite set + return Integer.MAX_VALUE; } - /** - * @throws IllegalStateException if the set is infinite in size - */ + /** @throws IllegalStateException if the set is infinite in size */ @Override public Object[] toArray() { if (this.map.units.isEmpty() || this.map.prefixes.isEmpty()) return super.toArray(); - else - // infinite set - throw new IllegalStateException( - "Cannot make an infinite set into an array."); + // infinite set + throw new IllegalStateException( + "Cannot make an infinite set into an array."); } - /** - * @throws IllegalStateException if the set is infinite in size - */ + /** @throws IllegalStateException if the set is infinite in size */ @Override public T[] toArray(final T[] a) { if (this.map.units.isEmpty() || this.map.prefixes.isEmpty()) return super.toArray(a); - else - // infinite set - throw new IllegalStateException( - "Cannot make an infinite set into an array."); + // infinite set + throw new IllegalStateException( + "Cannot make an infinite set into an array."); } @Override public String toString() { if (this.map.units.isEmpty() || this.map.prefixes.isEmpty()) return super.toString(); - else - return String.format( - "Infinite set of name-unit entries created from units %s and prefixes %s", - this.map.units, this.map.prefixes); + return String.format( + "Infinite set of name-unit entries created from units %s and prefixes %s", + this.map.units, this.map.prefixes); } } /** * The class used for unit name sets. - * + * *

* If the map that created this set is infinite in size (has at least one * unit and at least one prefix), this set is infinite as well. If this @@ -503,7 +489,7 @@ public final class UnitDatabase { * {@code IllegalStateException} instead of creating an infinite-sized * array. *

- * + * * @author Adrien Hopkins * @since 2019-04-13 * @since v0.2.0 @@ -513,7 +499,7 @@ public final class UnitDatabase { /** * An iterator that iterates over the units of a * {@code PrefixedUnitNameSet}. - * + * * @author Adrien Hopkins * @since 2019-04-14 * @since v0.2.0 @@ -533,9 +519,9 @@ public final class UnitDatabase { /** * Creates the * {@code UnitsDatabase.PrefixedUnitMap.PrefixedUnitNameSet.PrefixedUnitNameIterator}. - * + * * @param map map to base itorator on - * + * * @since 2019-04-14 * @since v0.2.0 */ @@ -551,7 +537,7 @@ public final class UnitDatabase { * @since v0.2.0 */ private String getCurrentUnitName() { - final StringBuilder unitName = new StringBuilder(); + final var unitName = new StringBuilder(); for (final int i : this.prefixCoordinates) { unitName.append(this.prefixNames.get(i)); } @@ -564,18 +550,15 @@ public final class UnitDatabase { public boolean hasNext() { if (this.unitNames.isEmpty()) return false; - else { - if (this.prefixNames.isEmpty()) - return this.prefixCoordinates.isEmpty() - && this.unitNamePosition < this.unitNames.size(); - else - return true; - } + if (this.prefixNames.isEmpty()) + return this.prefixCoordinates.isEmpty() + && this.unitNamePosition < this.unitNames.size(); + return true; } /** * Changes this iterator's position to the next available one. - * + * * @since 2019-04-14 * @since v0.2.0 */ @@ -591,7 +574,7 @@ public final class UnitDatabase { this.prefixCoordinates.add(0, 0); } else { // get the prefix coordinate to increment, then increment - int i = this.prefixCoordinates.size() - 1; + var i = this.prefixCoordinates.size() - 1; this.prefixCoordinates.set(i, this.prefixCoordinates.get(i) + 1); @@ -616,7 +599,7 @@ public final class UnitDatabase { @Override public String next() { - final String nextName = this.peek(); + final var nextName = this.peek(); this.incrementPosition(); @@ -649,7 +632,7 @@ public final class UnitDatabase { /** * Returns a string representation of the object. The exact details * of the representation are unspecified and subject to change. - * + * * @since 2019-05-03 * @since v0.3.0 */ @@ -666,7 +649,7 @@ public final class UnitDatabase { /** * Creates the {@code PrefixedUnitNameSet}. - * + * * @param map map that created this set * @since 2019-04-13 * @since v0.2.0 @@ -744,56 +727,46 @@ public final class UnitDatabase { public int size() { if (this.map.units.isEmpty()) return 0; - else { - if (this.map.prefixes.isEmpty()) - return this.map.units.size(); - else - // infinite set - return Integer.MAX_VALUE; - } + if (this.map.prefixes.isEmpty()) + return this.map.units.size(); + // infinite set + return Integer.MAX_VALUE; } - /** - * @throws IllegalStateException if the set is infinite in size - */ + /** @throws IllegalStateException if the set is infinite in size */ @Override public Object[] toArray() { if (this.map.units.isEmpty() || this.map.prefixes.isEmpty()) return super.toArray(); - else - // infinite set - throw new IllegalStateException( - "Cannot make an infinite set into an array."); + // infinite set + throw new IllegalStateException( + "Cannot make an infinite set into an array."); } - /** - * @throws IllegalStateException if the set is infinite in size - */ + /** @throws IllegalStateException if the set is infinite in size */ @Override public T[] toArray(final T[] a) { if (this.map.units.isEmpty() || this.map.prefixes.isEmpty()) return super.toArray(a); - else - // infinite set - throw new IllegalStateException( - "Cannot make an infinite set into an array."); + // infinite set + throw new IllegalStateException( + "Cannot make an infinite set into an array."); } @Override public String toString() { if (this.map.units.isEmpty() || this.map.prefixes.isEmpty()) return super.toString(); - else - return String.format( - "Infinite set of name-unit entries created from units %s and prefixes %s", - this.map.units, this.map.prefixes); + return String.format( + "Infinite set of name-unit entries created from units %s and prefixes %s", + this.map.units, this.map.prefixes); } } /** * The units stored in this collection, without prefixes. - * + * * @since 2019-04-13 * @since v0.2.0 */ @@ -801,7 +774,7 @@ public final class UnitDatabase { /** * The available prefixes for use. - * + * * @since 2019-04-13 * @since v0.2.0 */ @@ -814,7 +787,7 @@ public final class UnitDatabase { /** * Creates the {@code PrefixedUnitMap}. - * + * * @param units map mapping unit names to units * @param prefixes map mapping prefix names to prefixes * @since 2019-04-13 @@ -865,11 +838,11 @@ public final class UnitDatabase { if (!(key instanceof String)) throw new IllegalArgumentException( "Attempted to test for a unit using a non-string name."); - final String unitName = (String) key; + final var unitName = (String) key; // Then, look for the longest prefix that is attached to a valid unit String longestPrefix = null; - int longestLength = 0; + var longestLength = 0; for (final String prefixName : this.prefixes.keySet()) { // a prefix name is valid if: @@ -881,7 +854,7 @@ public final class UnitDatabase { // linear units can have prefixes) if (unitName.startsWith(prefixName) && prefixName.length() > longestLength) { - final String rest = unitName.substring(prefixName.length()); + final var rest = unitName.substring(prefixName.length()); if (this.containsKey(rest) && this.get(rest) instanceof LinearUnit) { longestPrefix = prefixName; @@ -895,7 +868,7 @@ public final class UnitDatabase { /** * {@inheritDoc} - * + * *

* Because of ambiguities between prefixes (i.e. kilokilo = mega), this * method only tests for prefixless units. @@ -924,11 +897,11 @@ public final class UnitDatabase { if (!(key instanceof String)) throw new IllegalArgumentException( "Attempted to obtain a unit using a non-string name."); - final String unitName = (String) key; + final var unitName = (String) key; // Then, look for the longest prefix that is attached to a valid unit String longestPrefix = null; - int longestLength = 0; + var longestLength = 0; for (final String prefixName : this.prefixes.keySet()) { // a prefix name is valid if: @@ -940,7 +913,7 @@ public final class UnitDatabase { // linear units can have prefixes) if (unitName.startsWith(prefixName) && prefixName.length() > longestLength) { - final String rest = unitName.substring(prefixName.length()); + final var rest = unitName.substring(prefixName.length()); if (this.containsKey(rest) && this.get(rest) instanceof LinearUnit) { longestPrefix = prefixName; @@ -952,16 +925,14 @@ public final class UnitDatabase { // if none found, returns null if (longestPrefix == null) return null; - else { - // get necessary data - final String rest = unitName.substring(longestLength); - // this cast will not fail because I verified that it would work - // before selecting this prefix - final LinearUnit unit = (LinearUnit) this.get(rest); - final UnitPrefix prefix = this.prefixes.get(longestPrefix); - - return unit.withPrefix(prefix); - } + // get necessary data + final var rest = unitName.substring(longestLength); + // this cast will not fail because I verified that it would work + // before selecting this prefix + final var unit = (LinearUnit) this.get(rest); + final var prefix = this.prefixes.get(longestPrefix); + + return unit.withPrefix(prefix); } @Override @@ -1038,28 +1009,24 @@ public final class UnitDatabase { public int size() { if (this.units.isEmpty()) return 0; - else { - if (this.prefixes.isEmpty()) - return this.units.size(); - else - // infinite set - return Integer.MAX_VALUE; - } + if (this.prefixes.isEmpty()) + return this.units.size(); + // infinite set + return Integer.MAX_VALUE; } @Override public String toString() { if (this.units.isEmpty() || this.prefixes.isEmpty()) return new HashMap<>(this).toString(); - else - return String.format( - "Infinite map of name-unit entries created from units %s and prefixes %s", - this.units, this.prefixes); + return String.format( + "Infinite map of name-unit entries created from units %s and prefixes %s", + this.units, this.prefixes); } /** * {@inheritDoc} - * + * *

* Because of ambiguities between prefixes (i.e. kilokilo = mega), this * method ignores prefixes. @@ -1090,60 +1057,60 @@ public final class UnitDatabase { /** * The exponent operator - * + * * @param base base of exponentiation * @param exponentUnit exponent * @return result * @since 2019-04-10 * @since v0.2.0 */ - private static final LinearUnit exponentiateUnits(final LinearUnit base, + private static LinearUnit exponentiateUnits(final LinearUnit base, final LinearUnit exponentUnit) { if (!exponentUnit.getBase().equals(Metric.ONE.getBase())) throw new IllegalArgumentException(String.format( "Tried to exponentiate %s^%s, but exponents must be dimensionless numbers.", base, exponentUnit)); - final double exponent = exponentUnit.getConversionFactor(); + final var exponent = exponentUnit.getConversionFactor(); return base.toExponentRounded(exponent); } /** * The exponent operator - * + * * @param base base of exponentiation * @param exponentUnit exponent * @return result * @since 2020-08-04 * @since v0.3.0 */ - private static final LinearUnitValue exponentiateUnitValues( + private static LinearUnitValue exponentiateUnitValues( final LinearUnitValue base, final LinearUnitValue exponentValue) { if (!exponentValue.canConvertTo(Metric.ONE)) throw new IllegalArgumentException(String.format( "Tried to exponentiate %s^%s, but exponents must be dimensionless numbers.", base, exponentValue)); - final double exponent = exponentValue.getValueExact(); + final var exponent = exponentValue.getValueExact(); return base.toExponentRounded(exponent); } /** * Formats an expression so it can be parsed by the expression parser. - * + * * Specifically, puts spaces around all operators so they can be parsed as * words. - * + * * @param expression expression to format * @return formatted expression * @since 2025-06-07 * @since v1.0.0 */ - static final String formatExpression(String expression) { - String modifiedExpression = expression; + static String formatExpression(String expression) { + var modifiedExpression = expression; for (final String operator : Arrays.asList("\\*", "/", "\\|", "\\^")) { - modifiedExpression = modifiedExpression.replaceAll( - operator, " " + operator + " "); + modifiedExpression = modifiedExpression.replaceAll(operator, + " " + operator + " "); } modifiedExpression = modifiedExpression.replaceAll("\\s+", " "); @@ -1158,8 +1125,8 @@ public final class UnitDatabase { static boolean isRemovableDuplicate(Map map, Entry entry) { for (final Entry e : map.entrySet()) { - final String name = e.getKey(); - final T value = e.getValue(); + final var name = e.getKey(); + final var value = e.getValue(); if (lengthFirstComparator.compare(entry.getKey(), name) < 0 && Objects.equals(map.get(entry.getKey()), value)) return true; @@ -1169,7 +1136,7 @@ public final class UnitDatabase { /** * The units in this system, excluding prefixes. - * + * * @since 2019-01-07 * @since v0.1.0 */ @@ -1177,7 +1144,7 @@ public final class UnitDatabase { /** * The unit prefixes in this system. - * + * * @since 2019-01-14 * @since v0.1.0 */ @@ -1185,7 +1152,7 @@ public final class UnitDatabase { /** * The dimensions in this system. - * + * * @since 2019-03-14 * @since v0.2.0 */ @@ -1193,7 +1160,7 @@ public final class UnitDatabase { /** * A map mapping strings to units (including prefixes) - * + * * @since 2019-04-13 * @since v0.2.0 */ @@ -1201,7 +1168,7 @@ public final class UnitDatabase { /** * A map mapping strings to unit sets - * + * * @since 2024-08-16 * @since v1.0.0 */ @@ -1221,74 +1188,74 @@ public final class UnitDatabase { /** * A parser that can parse unit expressions. - * + * * @since 2019-03-22 * @since v0.2.0 */ private final ExpressionParser unitExpressionParser = new ExpressionParser.Builder<>( - this::getLinearUnit).addBinaryOperator("+", (o1, o2) -> o1.plus(o2), 0) - .addBinaryOperator("-", (o1, o2) -> o1.minus(o2), 0) - .addBinaryOperator("*", (o1, o2) -> o1.times(o2), 1) - .addBinaryOperator("space_times", (o1, o2) -> o1.times(o2), 2) + this::getLinearUnit).addBinaryOperator("+", LinearUnit::plus, 0) + .addBinaryOperator("-", LinearUnit::minus, 0) + .addBinaryOperator("*", LinearUnit::times, 1) + .addBinaryOperator("space_times", LinearUnit::times, 2) .addSpaceFunction("space_times") - .addBinaryOperator("/", (o1, o2) -> o1.dividedBy(o2), 1) - .addBinaryOperator("|", (o1, o2) -> o1.dividedBy(o2), 4) + .addBinaryOperator("/", LinearUnit::dividedBy, 1) + .addBinaryOperator("|", LinearUnit::dividedBy, 4) .addBinaryOperator("^", UnitDatabase::exponentiateUnits, 3).build(); /** * A parser that can parse unit value expressions. - * + * * @since 2020-08-04 * @since v0.3.0 */ private final ExpressionParser unitValueExpressionParser = new ExpressionParser.Builder<>( this::getLinearUnitValue) - .addBinaryOperator("+", (o1, o2) -> o1.plus(o2), 0) - .addBinaryOperator("-", (o1, o2) -> o1.minus(o2), 0) - .addBinaryOperator("*", (o1, o2) -> o1.times(o2), 1) - .addBinaryOperator("space_times", (o1, o2) -> o1.times(o2), 2) + .addBinaryOperator("+", LinearUnitValue::plus, 0) + .addBinaryOperator("-", LinearUnitValue::minus, 0) + .addBinaryOperator("*", LinearUnitValue::times, 1) + .addBinaryOperator("space_times", LinearUnitValue::times, 2) .addSpaceFunction("space_times") - .addBinaryOperator("/", (o1, o2) -> o1.dividedBy(o2), 1) - .addBinaryOperator("|", (o1, o2) -> o1.dividedBy(o2), 4) + .addBinaryOperator("/", LinearUnitValue::dividedBy, 1) + .addBinaryOperator("|", LinearUnitValue::dividedBy, 4) .addBinaryOperator("^", UnitDatabase::exponentiateUnitValues, 3) .build(); /** * A parser that can parse unit prefix expressions - * + * * @since 2019-04-13 * @since v0.2.0 */ private final ExpressionParser prefixExpressionParser = new ExpressionParser.Builder<>( - this::getPrefix).addBinaryOperator("+", (o1, o2) -> o1.plus(o2), 0) - .addBinaryOperator("-", (o1, o2) -> o1.minus(o2), 0) - .addBinaryOperator("*", (o1, o2) -> o1.times(o2), 1) + this::getPrefix).addBinaryOperator("+", UnitPrefix::plus, 0) + .addBinaryOperator("-", UnitPrefix::minus, 0) + .addBinaryOperator("*", UnitPrefix::times, 1) .addSpaceFunction("*") - .addBinaryOperator("/", (o1, o2) -> o1.dividedBy(o2), 1) - .addBinaryOperator("|", (o1, o2) -> o1.dividedBy(o2), 3) + .addBinaryOperator("/", UnitPrefix::dividedBy, 1) + .addBinaryOperator("|", UnitPrefix::dividedBy, 3) .addBinaryOperator("^", (o1, o2) -> o1.toExponent(o2.getMultiplier()), 2) .build(); /** * A parser that can parse unit dimension expressions. - * + * * @since 2019-04-13 * @since v0.2.0 */ private final ExpressionParser> unitDimensionParser = new ExpressionParser.Builder<>( - this::getDimension).addBinaryOperator("*", (o1, o2) -> o1.times(o2), 0) + this::getDimension).addBinaryOperator("*", ObjectProduct::times, 0) .addSpaceFunction("*") - .addBinaryOperator("/", (o1, o2) -> o1.dividedBy(o2), 0) - .addBinaryOperator("|", (o1, o2) -> o1.dividedBy(o2), 2) + .addBinaryOperator("/", ObjectProduct::dividedBy, 0) + .addBinaryOperator("|", ObjectProduct::dividedBy, 2) .addNumericOperator("^", (o1, o2) -> { - final int exponent = (int) Math.round(o2.value()); + final var exponent = (int) Math.round(o2.value()); return o1.toExponent(exponent); }, 1).build(); /** * Creates the {@code UnitsDatabase}. - * + * * @since 2019-01-10 * @since v0.1.0 */ @@ -1298,7 +1265,7 @@ public final class UnitDatabase { /** * Creates the {@code UnitsDatabase} - * + * * @param prefixRepetitionRule the rule that determines when prefix * repetition is allowed * @since 2020-08-26 @@ -1318,7 +1285,7 @@ public final class UnitDatabase { /** * Adds a unit dimension to the database. - * + * * @param name dimension's name * @param dimension dimension to add * @throws NullPointerException if name or dimension is null @@ -1329,14 +1296,14 @@ public final class UnitDatabase { final ObjectProduct dimension) { Objects.requireNonNull(name, "name may not be null"); Objects.requireNonNull(dimension, "dimension may not be null"); - final ObjectProduct namedDimension = dimension + final var namedDimension = dimension .withName(dimension.getNameSymbol().withExtraName(name)); this.dimensions.put(name, namedDimension); } /** * Adds to the list from a line in a unit dimension file. - * + * * @param line line to look at * @param lineCounter number of line, for error messages * @since 2019-04-10 @@ -1354,13 +1321,13 @@ public final class UnitDatabase { } // divide line into name and expression - final Matcher lineMatcher = NAME_EXPRESSION.matcher(line); + final var lineMatcher = NAME_EXPRESSION.matcher(line); if (!lineMatcher.matches()) throw new IllegalArgumentException(String.format( "Error at line %d: Lines of a dimension file must consist of a dimension name, then spaces or tabs, then a dimension expression.", lineCounter)); - final String name = lineMatcher.group(1); - final String expression = lineMatcher.group(2); + final var name = lineMatcher.group(1); + final var expression = lineMatcher.group(2); // if (name.endsWith(" ")) { // System.err.printf("Warning - line %d's dimension name ends in a space", @@ -1380,7 +1347,7 @@ public final class UnitDatabase { /** * Adds a unit prefix to the database. - * + * * @param name prefix's name * @param prefix prefix to add * @throws NullPointerException if name or prefix is null @@ -1397,7 +1364,7 @@ public final class UnitDatabase { /** * Adds a unit to the database. - * + * * @param name unit's name * @param unit unit to add * @throws NullPointerException if unit is null @@ -1414,7 +1381,7 @@ public final class UnitDatabase { /** * Adds to the list from a line in a unit file. - * + * * @param line line to look at * @param lineCounter number of line, for error messages * @since 2019-04-10 @@ -1432,14 +1399,14 @@ public final class UnitDatabase { } // divide line into name and expression - final Matcher lineMatcher = NAME_EXPRESSION.matcher(line); + final var lineMatcher = NAME_EXPRESSION.matcher(line); if (!lineMatcher.matches()) throw new IllegalArgumentException(String.format( "Error at line %d: Lines of a unit file must consist of a unit name, then spaces or tabs, then a unit expression.", lineCounter)); - final String name = lineMatcher.group(1); + final var name = lineMatcher.group(1); - final String expression = lineMatcher.group(2); + final var expression = lineMatcher.group(2); // this code should never occur // if (name.endsWith(" ")) { @@ -1453,18 +1420,15 @@ public final class UnitDatabase { if (!this.containsUnitName(name)) throw new IllegalArgumentException(String .format("! used but no unit found (line %d).", lineCounter)); + } else if (name.endsWith("-")) { + final var prefixName = name.substring(0, name.length() - 1); + this.addPrefix(prefixName, this.getPrefixFromExpression(expression)); + } else if (expression.contains(";")) { + // it's a multi-unit + this.addUnitSet(name, this.getUnitSetFromExpression(expression)); } else { - if (name.endsWith("-")) { - final String prefixName = name.substring(0, name.length() - 1); - this.addPrefix(prefixName, - this.getPrefixFromExpression(expression)); - } else if (expression.contains(";")) { - // it's a multi-unit - this.addUnitSet(name, this.getUnitSetFromExpression(expression)); - } else { - // it's a unit, get the unit - this.addUnit(name, this.getUnitFromExpression(expression)); - } + // it's a unit, get the unit + this.addUnit(name, this.getUnitFromExpression(expression)); } } @@ -1491,7 +1455,7 @@ public final class UnitDatabase { /** * Removes all units, unit sets, prefixes and dimensions from this database. - * + * * @since 2022-02-26 * @since v0.4.0 */ @@ -1504,7 +1468,7 @@ public final class UnitDatabase { /** * Tests if the database has a unit dimension with this name. - * + * * @param name name to test * @return if database contains name * @since 2019-03-14 @@ -1516,7 +1480,7 @@ public final class UnitDatabase { /** * Tests if the database has a unit prefix with this name. - * + * * @param name name to test * @return if database contains name * @since 2019-01-13 @@ -1529,7 +1493,7 @@ public final class UnitDatabase { /** * Tests if the database has a unit with this name, taking prefixes into * consideration - * + * * @param name name to test * @return if database contains name * @since 2019-01-13 @@ -1541,7 +1505,7 @@ public final class UnitDatabase { /** * Returns true iff there is a unit set with this name. - * + * * @param name name to check for * @return true iff there is a unit set with this name * @@ -1564,7 +1528,7 @@ public final class UnitDatabase { /** * Evaluates a unit expression, following the same rules as * {@link #getUnitFromExpression}. - * + * * @param expression expression to parse * @return {@code LinearUnitValue} representing value of expression * @since 2020-08-04 @@ -1583,7 +1547,7 @@ public final class UnitDatabase { /** * Gets a unit dimension from the database using its name. - * + * * @param name dimension's name * @return dimension * @since 2019-03-14 @@ -1591,12 +1555,11 @@ public final class UnitDatabase { */ public ObjectProduct getDimension(final String name) { Objects.requireNonNull(name, "name must not be null."); - final ObjectProduct dimension = this.dimensions.get(name); + final var dimension = this.dimensions.get(name); if (dimension == null) throw new NoSuchElementException( "No dimension with name \"" + name + "\"."); - else - return dimension; + return dimension; } /** @@ -1611,7 +1574,7 @@ public final class UnitDatabase { * multiplication) *

  • The operator '^' which exponentiates. Exponents must be integers.
  • * - * + * * @param expression expression to parse * @return parsed unit dimension * @throws IllegalArgumentException if the expression cannot be parsed @@ -1627,13 +1590,14 @@ public final class UnitDatabase { if (this.containsDimensionName(expression)) return this.getDimension(expression); - return this.unitDimensionParser.parseExpression(formatExpression(expression)); + return this.unitDimensionParser + .parseExpression(formatExpression(expression)); } /** * Gets a unit. If it is linear, cast it to a LinearUnit and return it. * Otherwise, throw an {@code IllegalArgumentException}. - * + * * @param name unit's name * @return unit * @since 2019-03-22 @@ -1650,26 +1614,25 @@ public final class UnitDatabase { "Format nonlinear units like: unit(value)."); // solve the function - final Unit unit = this.getUnit(parts.get(0)); - final double value = Double.parseDouble( + final var unit = this.getUnit(parts.get(0)); + final var value = Double.parseDouble( parts.get(1).substring(0, parts.get(1).length() - 1)); return LinearUnit.fromUnitValue(unit, value); - } else { - // get a linear unit - final Unit unit = this.getUnit(name); - - if (unit instanceof LinearUnit) - return (LinearUnit) unit; - else - throw new IllegalArgumentException( - String.format("%s is not a linear unit.", name)); } + // get a linear unit + final var unit = this.getUnit(name); + + if (unit instanceof LinearUnit) + return (LinearUnit) unit; + else + throw new IllegalArgumentException( + String.format("%s is not a linear unit.", name)); } /** * Gets a {@code LinearUnitValue} from a unit name. Nonlinear units will be * converted to their base units. - * + * * @param name name of unit * @return {@code LinearUnitValue} instance * @since 2020-08-04 @@ -1687,7 +1650,7 @@ public final class UnitDatabase { /** * Gets a unit prefix from the database from its name - * + * * @param name prefix's name * @return prefix * @since 2019-01-10 @@ -1697,18 +1660,17 @@ public final class UnitDatabase { try { return UnitPrefix.valueOf(Double.parseDouble(name)); } catch (final NumberFormatException e) { - final UnitPrefix prefix = this.prefixes.get(name); + final var prefix = this.prefixes.get(name); if (prefix == null) throw new NoSuchElementException( "No prefix with name \"" + name + "\"."); - else - return prefix; + return prefix; } } /** * Gets all of the prefixes that are on a unit name, in application order. - * + * * @param unitName name of unit * @return prefixes * @since 2020-08-26 @@ -1716,12 +1678,12 @@ public final class UnitDatabase { */ List getPrefixesFromName(final String unitName) { final List prefixes = new ArrayList<>(); - String name = unitName; + var name = unitName; while (!this.prefixlessUnits.containsKey(name)) { // find the longest prefix String longestPrefixName = null; - int longestLength = name.length(); + var longestLength = name.length(); while (longestPrefixName == null) { longestLength--; @@ -1734,7 +1696,7 @@ public final class UnitDatabase { } // longest prefix found! - final UnitPrefix prefix = this.getPrefix(longestPrefixName); + final var prefix = this.getPrefix(longestPrefixName); prefixes.add(0, prefix); name = name.substring(longestLength); } @@ -1747,7 +1709,7 @@ public final class UnitDatabase { * Currently, prefix expressions are much simpler than unit expressions: They * are either a number or the name of another prefix *

    - * + * * @param expression expression to input * @return prefix * @throws IllegalArgumentException if expression cannot be parsed @@ -1762,7 +1724,8 @@ public final class UnitDatabase { if (this.containsUnitName(expression)) return this.getPrefix(expression); - return this.prefixExpressionParser.parseExpression(formatExpression(expression)); + return this.prefixExpressionParser + .parseExpression(formatExpression(expression)); } /** @@ -1770,13 +1733,13 @@ public final class UnitDatabase { * @since 2020-08-26 * @since v0.3.0 */ - public final Predicate> getPrefixRepetitionRule() { + public Predicate> getPrefixRepetitionRule() { return this.prefixRepetitionRule; } /** * Gets a unit from the database from its name, looking for prefixes. - * + * * @param name unit's name * @return unit * @since 2019-01-10 @@ -1784,27 +1747,28 @@ public final class UnitDatabase { */ public Unit getUnit(final String name) { try { - final double value = Double.parseDouble(name); + final var value = Double.parseDouble(name); return Metric.ONE.times(value); } catch (final NumberFormatException e) { - final Unit unit = this.units.get(name); + final var unit = this.units.get(name); if (unit == null) throw new NoSuchElementException("No unit " + name); - else if (unit.getPrimaryName().isEmpty()) + if (unit.getPrimaryName().isEmpty()) return unit.withName(NameSymbol.ofName(name)); - else if (!unit.getPrimaryName().get().equals(name)) { + if (!unit.getPrimaryName().get().equals(name)) { final Set otherNames = new HashSet<>(unit.getOtherNames()); otherNames.add(unit.getPrimaryName().get()); return unit.withName(NameSymbol.ofNullable(name, unit.getSymbol().orElse(null), otherNames)); - } else if (!unit.getOtherNames().contains(name)) { + } + if (!unit.getOtherNames().contains(name)) { final Set otherNames = new HashSet<>(unit.getOtherNames()); otherNames.add(name); return unit.withName( NameSymbol.ofNullable(unit.getPrimaryName().orElse(null), unit.getSymbol().orElse(null), otherNames)); - } else - return unit; + } + return unit; } } @@ -1823,7 +1787,7 @@ public final class UnitDatabase { *
  • A number which is multiplied or divided
  • * * This method only works with linear units. - * + * * @param expression expression to parse * @return parsed unit * @throws IllegalArgumentException if the expression cannot be parsed @@ -1845,7 +1809,7 @@ public final class UnitDatabase { /** * Get a unit set from its name, throwing a {@link NoSuchElementException} if * there is none. - * + * * @param name name of unit set * @return unit set with that name * @@ -1853,7 +1817,7 @@ public final class UnitDatabase { * @since v1.0.0 */ public List getUnitSet(String name) { - final List unitSet = this.unitSets.get(name); + final var unitSet = this.unitSets.get(name); if (unitSet == null) throw new NoSuchElementException("No unit set with name " + name); return unitSet; @@ -1866,20 +1830,19 @@ public final class UnitDatabase { * @since v1.0.0 */ List getUnitSetFromExpression(String expression) { - final String[] parts = expression.split(";"); + final var parts = expression.split(";"); final List units = new ArrayList<>(parts.length); for (final String unitName : parts) { - final Unit unit = this.getUnitFromExpression(unitName.trim()); + final var unit = this.getUnitFromExpression(unitName.trim()); - if (!(unit instanceof LinearUnit)) { + if (!(unit instanceof LinearUnit)) throw new IllegalArgumentException(String.format( "Unit '%s' is in a unit-set expression, but is not linear.", unitName)); - } else if (units.size() > 0 && !unit.canConvertTo(units.get(0))) { + if (units.size() > 0 && !unit.canConvertTo(units.get(0))) throw new IllegalArgumentException(String.format( "Units in expression '%s' have different dimensions.", expression)); - } units.add((LinearUnit) unit); } @@ -1904,7 +1867,7 @@ public final class UnitDatabase { * no unit is found, an IllegalArgumentException is thrown. This is used to * define initial units and ensure that the database contains them. * - * + * * @param file file to read * @throws NullPointerException if file is null * @return list of errors that happened when loading file @@ -1915,7 +1878,7 @@ public final class UnitDatabase { Objects.requireNonNull(file, "file must not be null."); final List errors = new ArrayList<>(); try { - long lineCounter = 0; + var lineCounter = 0L; for (final String line : Files.readAllLines(file)) { try { this.addDimensionFromLine(line, ++lineCounter); @@ -1944,10 +1907,10 @@ public final class UnitDatabase { public List loadDimensionsFromStream( final InputStream stream) { final List errors = new ArrayList<>(); - try (final Scanner scanner = new Scanner(stream)) { - long lineCounter = 0; + try (final var scanner = new Scanner(stream)) { + var lineCounter = 0L; while (scanner.hasNextLine()) { - final String line = scanner.nextLine(); + final var line = scanner.nextLine(); try { this.addDimensionFromLine(line, ++lineCounter); } catch (IllegalArgumentException | NoSuchElementException e) { @@ -1976,7 +1939,7 @@ public final class UnitDatabase { * no unit is found, an IllegalArgumentException is thrown. This is used to * define initial units and ensure that the database contains them. * - * + * * @param file file to read * @throws NullPointerException if file is null * @return list of errors that happened when loading file @@ -1987,7 +1950,7 @@ public final class UnitDatabase { Objects.requireNonNull(file, "file must not be null."); final List errors = new ArrayList<>(); try { - long lineCounter = 0; + var lineCounter = 0L; for (final String line : Files.readAllLines(file)) { try { this.addUnitOrPrefixFromLine(line, ++lineCounter); @@ -2015,10 +1978,10 @@ public final class UnitDatabase { */ public List loadUnitsFromStream(InputStream stream) { final List errors = new ArrayList<>(); - try (final Scanner scanner = new Scanner(stream)) { - long lineCounter = 0; + try (final var scanner = new Scanner(stream)) { + var lineCounter = 0L; while (scanner.hasNextLine()) { - final String line = scanner.nextLine(); + final var line = scanner.nextLine(); try { this.addUnitOrPrefixFromLine(line, ++lineCounter); } catch (IllegalArgumentException | NoSuchElementException e) { @@ -2039,10 +2002,9 @@ public final class UnitDatabase { public Map prefixMap(boolean includeDuplicates) { if (includeDuplicates) return Collections.unmodifiableMap(this.prefixes); - else - return Collections.unmodifiableMap(ConditionalExistenceCollections - .conditionalExistenceMap(this.prefixes, - entry -> !isRemovableDuplicate(this.prefixes, entry))); + return Collections.unmodifiableMap(ConditionalExistenceCollections + .conditionalExistenceMap(this.prefixes, + entry -> !isRemovableDuplicate(this.prefixes, entry))); } /** @@ -2050,7 +2012,7 @@ public final class UnitDatabase { * @since 2020-08-26 * @since v0.3.0 */ - public final void setPrefixRepetitionRule( + public void setPrefixRepetitionRule( Predicate> prefixRepetitionRule) { this.prefixRepetitionRule = prefixRepetitionRule; } @@ -2089,7 +2051,7 @@ public final class UnitDatabase { * {@link PrefixedUnitMap#values() values()} methods currently ignore * prefixes. *

    - * + * * @return a map mapping unit names to units, including prefixed names * @since 2019-04-13 * @since v0.2.0 @@ -2110,11 +2072,9 @@ public final class UnitDatabase { public Map unitMapPrefixless(boolean includeDuplicates) { if (includeDuplicates) return Collections.unmodifiableMap(this.prefixlessUnits); - else - return Collections.unmodifiableMap(ConditionalExistenceCollections - .conditionalExistenceMap(this.prefixlessUnits, - entry -> !isRemovableDuplicate(this.prefixlessUnits, - entry))); + return Collections.unmodifiableMap(ConditionalExistenceCollections + .conditionalExistenceMap(this.prefixlessUnits, + entry -> !isRemovableDuplicate(this.prefixlessUnits, entry))); } /** diff --git a/src/main/java/sevenUnits/unit/UnitPrefix.java b/src/main/java/sevenUnits/unit/UnitPrefix.java index 0fd3421..af106b9 100644 --- a/src/main/java/sevenUnits/unit/UnitPrefix.java +++ b/src/main/java/sevenUnits/unit/UnitPrefix.java @@ -25,7 +25,7 @@ import sevenUnits.utils.Nameable; /** * A prefix that can be applied to a {@code LinearUnit} to multiply it by some * value - * + * * @author Adrien Hopkins * @since 2019-10-16 * @since v0.3.0 @@ -33,7 +33,7 @@ import sevenUnits.utils.Nameable; public final class UnitPrefix implements Nameable { /** * Gets a {@code UnitPrefix} from a multiplier - * + * * @param multiplier multiplier of prefix * @return prefix * @since 2019-10-16 @@ -45,7 +45,7 @@ public final class UnitPrefix implements Nameable { /** * Gets a {@code UnitPrefix} from a multiplier and a name - * + * * @param multiplier multiplier of prefix * @param ns name(s) and symbol of prefix * @return prefix @@ -61,7 +61,7 @@ public final class UnitPrefix implements Nameable { /** * This prefix's name(s) and symbol. - * + * * @since 2022-04-16 * @since v0.4.0 */ @@ -69,7 +69,7 @@ public final class UnitPrefix implements Nameable { /** * The number that this prefix multiplies units by - * + * * @since 2019-10-16 * @since v0.3.0 */ @@ -77,7 +77,7 @@ public final class UnitPrefix implements Nameable { /** * Creates the {@code DefaultUnitPrefix}. - * + * * @param multiplier * @since 2019-01-14 * @since v0.2.0 @@ -89,7 +89,7 @@ public final class UnitPrefix implements Nameable { /** * Divides this prefix by a scalar - * + * * @param divisor number to divide by * @return quotient of prefix and scalar * @since 2019-10-16 @@ -101,7 +101,7 @@ public final class UnitPrefix implements Nameable { /** * Divides this prefix by {@code other}. - * + * * @param other prefix to divide by * @return quotient of prefixes * @since 2019-04-13 @@ -113,29 +113,26 @@ public final class UnitPrefix implements Nameable { /** * {@inheritDoc} - * + * * Uses the prefix's multiplier to determine equality. */ @Override public boolean equals(final Object obj) { if (this == obj) return true; - if (obj == null) - return false; - if (!(obj instanceof UnitPrefix)) + if ((obj == null) || !(obj instanceof UnitPrefix)) return false; - final UnitPrefix other = (UnitPrefix) obj; - return Double.compare(this.getMultiplier(), - other.getMultiplier()) == 0; + final var other = (UnitPrefix) obj; + return Double.compare(this.getMultiplier(), other.getMultiplier()) == 0; } /** * @param other prefix to compare to - * @return true iff this prefix and other are equal, - * ignoring small differences caused by floating-point error. - * - * @apiNote This method is not transitive, - * so it cannot be used as an equals method. + * @return true iff this prefix and other are equal, ignoring small + * differences caused by floating-point error. + * + * @apiNote This method is not transitive, so it cannot be used as an equals + * method. */ public boolean equalsApproximately(final UnitPrefix other) { if (this == other) @@ -162,7 +159,7 @@ public final class UnitPrefix implements Nameable { /** * {@inheritDoc} - * + * * Uses the prefix's multiplier to determine a hash code. */ @Override @@ -171,22 +168,24 @@ public final class UnitPrefix implements Nameable { } /** - * Multiplies this prefix by a scalar - * - * @param multiplicand number to multiply by - * @return product of prefix and scalar - * @since 2019-10-16 - * @since v0.3.0 + * Subtracts {@code other} from this prefix and returns the result. + * + * @param other prefix to subtract + * @return difference of prefixes + * + * @since 2024-03-03 + * @since v0.5.0 */ - public UnitPrefix times(final double multiplicand) { - return valueOf(this.getMultiplier() * multiplicand); + public UnitPrefix minus(final UnitPrefix other) { + return valueOf(this.getMultiplier() - other.getMultiplier()); } /** * Adds {@code other} to this prefix and returns the result. + * * @param other prefix to add * @return sum of prefixes - * + * * @since 2024-03-03 * @since v0.5.0 */ @@ -195,20 +194,20 @@ public final class UnitPrefix implements Nameable { } /** - * Subtracts {@code other} from this prefix and returns the result. - * @param other prefix to subtract - * @return difference of prefixes - * - * @since 2024-03-03 - * @since v0.5.0 + * Multiplies this prefix by a scalar + * + * @param multiplicand number to multiply by + * @return product of prefix and scalar + * @since 2019-10-16 + * @since v0.3.0 */ - public UnitPrefix minus(final UnitPrefix other) { - return valueOf(this.getMultiplier() - other.getMultiplier()); + public UnitPrefix times(final double multiplicand) { + return valueOf(this.getMultiplier() * multiplicand); } /** * Multiplies this prefix by {@code other}. - * + * * @param other prefix to multiply by * @return product of prefixes * @since 2019-04-13 @@ -220,7 +219,7 @@ public final class UnitPrefix implements Nameable { /** * Raises this prefix to an exponent. - * + * * @param exponent exponent to raise to * @return result of exponentiation. * @since 2019-04-13 @@ -230,19 +229,16 @@ public final class UnitPrefix implements Nameable { return valueOf(Math.pow(this.getMultiplier(), exponent)); } - /** - * @return a string describing the prefix and its multiplier - */ + /** @return a string describing the prefix and its multiplier */ @Override public String toString() { if (this.getPrimaryName().isPresent()) return String.format("%s (\u00D7 %s)", this.getPrimaryName().get(), this.multiplier); - else if (this.getSymbol().isPresent()) + if (this.getSymbol().isPresent()) return String.format("%s (\u00D7 %s)", this.getSymbol().get(), this.multiplier); - else - return String.format("Unit Prefix (\u00D7 %s)", this.multiplier); + return String.format("Unit Prefix (\u00D7 %s)", this.multiplier); } /** diff --git a/src/main/java/sevenUnits/unit/UnitType.java b/src/main/java/sevenUnits/unit/UnitType.java index a331d3d..b195f13 100644 --- a/src/main/java/sevenUnits/unit/UnitType.java +++ b/src/main/java/sevenUnits/unit/UnitType.java @@ -57,9 +57,8 @@ public enum UnitType { public static final UnitType getType(Unit u, Predicate isSemiMetric) { if (isSemiMetric.test(u)) return SEMI_METRIC; - else if (u.isMetric()) + if (u.isMetric()) return METRIC; - else - return NON_METRIC; + return NON_METRIC; } } diff --git a/src/main/java/sevenUnits/unit/UnitValue.java b/src/main/java/sevenUnits/unit/UnitValue.java index 4003c17..e24b6e2 100644 --- a/src/main/java/sevenUnits/unit/UnitValue.java +++ b/src/main/java/sevenUnits/unit/UnitValue.java @@ -17,16 +17,15 @@ package sevenUnits.unit; import java.util.Objects; -import java.util.Optional; import sevenUnits.utils.NameSymbol; /** * A value expressed in a unit. - * + * * Unless otherwise indicated, all methods in this class throw a * {@code NullPointerException} when an argument is null. - * + * * @author Adrien Hopkins * @since 2020-07-26 * @since v0.3.0 @@ -34,7 +33,7 @@ import sevenUnits.utils.NameSymbol; public final class UnitValue { /** * Creates a {@code UnitValue} from a unit and the associated value. - * + * * @param unit unit to use * @param value value to use * @return {@code UnitValue} instance @@ -62,18 +61,18 @@ public final class UnitValue { * @since 2020-10-01 * @since v0.3.0 */ - public final boolean canConvertTo(Unit other) { + public boolean canConvertTo(Unit other) { return this.unit.canConvertTo(other); } /** * Returns a UnitValue that represents the same value expressed in a * different unit - * + * * @param other new unit to express value in * @return value expressed in {@code other} */ - public final UnitValue convertTo(Unit other) { + public UnitValue convertTo(Unit other) { return UnitValue.of(other, this.getUnit().convertTo(other, this.getValue())); } @@ -88,8 +87,8 @@ public final class UnitValue { * @since 2020-09-29 * @since v0.3.0 */ - public final LinearUnitValue convertToBase(NameSymbol ns) { - final LinearUnit base = LinearUnit.getBase(this.unit).withName(ns); + public LinearUnitValue convertToBase(NameSymbol ns) { + final var base = LinearUnit.getBase(this.unit).withName(ns); return this.convertToLinear(base); } @@ -100,7 +99,7 @@ public final class UnitValue { * @since 2020-09-29 * @since v0.3.0 */ - public final LinearUnitValue convertToLinear(LinearUnit newUnit) { + public LinearUnitValue convertToLinear(LinearUnit newUnit) { return LinearUnitValue.getExact(newUnit, this.getUnit().convertTo(newUnit, this.getValue())); } @@ -114,7 +113,7 @@ public final class UnitValue { public boolean equals(Object obj) { if (!(obj instanceof UnitValue)) return false; - final UnitValue other = (UnitValue) obj; + final var other = (UnitValue) obj; return Objects.equals(this.getUnit().getBase(), other.getUnit().getBase()) && Double.doubleToLongBits( this.getUnit().convertToBase(this.getValue())) == Double @@ -127,7 +126,7 @@ public final class UnitValue { * @since 2020-09-29 * @since v0.3.0 */ - public final Unit getUnit() { + public Unit getUnit() { return this.unit; } @@ -136,7 +135,7 @@ public final class UnitValue { * @since 2020-09-29 * @since v0.3.0 */ - public final double getValue() { + public double getValue() { return this.value; } @@ -148,16 +147,15 @@ public final class UnitValue { @Override public String toString() { - final Optional primaryName = this.getUnit().getPrimaryName(); - final Optional symbol = this.getUnit().getSymbol(); + final var primaryName = this.getUnit().getPrimaryName(); + final var symbol = this.getUnit().getSymbol(); if (primaryName.isEmpty() && symbol.isEmpty()) { - final double baseValue = this.getUnit().convertToBase(this.getValue()); + final var baseValue = this.getUnit().convertToBase(this.getValue()); return String.format("%s unnamed unit (= %s %s)", this.getValue(), baseValue, this.getUnit().getBase() .toString(unit -> unit.getSymbol().orElseThrow())); - } else { - final String unitName = symbol.orElse(primaryName.get()); - return this.getValue() + " " + unitName; } + final var unitName = symbol.orElse(primaryName.get()); + return this.getValue() + " " + unitName; } } diff --git a/src/main/java/sevenUnits/unit/package-info.java b/src/main/java/sevenUnits/unit/package-info.java index 6d867d3..c650b58 100644 --- a/src/main/java/sevenUnits/unit/package-info.java +++ b/src/main/java/sevenUnits/unit/package-info.java @@ -16,7 +16,7 @@ */ /** * Everything to do with the units that make up Unit Converter. - * + * * @author Adrien Hopkins * @since 2019-10-16 * @since v0.1.0 -- cgit v1.2.3