Minestom/src/main/java/net/minestom/server/command/builder/arguments/minecraft/ArgumentFloatRange.java

79 lines
2.4 KiB
Java
Raw Normal View History

package net.minestom.server.command.builder.arguments.minecraft;
import net.minestom.server.utils.math.FloatRange;
2020-10-24 16:58:27 +02:00
import org.jetbrains.annotations.NotNull;
import java.util.regex.Pattern;
2020-07-11 14:16:36 +02:00
/**
2020-10-17 11:29:05 +02:00
* Represents an argument which will give you an {@link FloatRange}.
* <p>
* Example: ..3, 3.., 5..10, 15
2020-07-11 14:16:36 +02:00
*/
2020-07-11 00:38:39 +02:00
public class ArgumentFloatRange extends ArgumentRange<FloatRange> {
public ArgumentFloatRange(String id) {
super(id);
}
@Override
2020-10-24 16:58:27 +02:00
public int getCorrectionResult(@NotNull String value) {
try {
Float.valueOf(value);
return SUCCESS; // Is a single number
} catch (NumberFormatException e) {
String[] split = value.split(Pattern.quote(".."));
2020-07-11 00:38:39 +02:00
if (split.length == 1) {
try {
2020-07-11 14:16:36 +02:00
Float.valueOf(split[0]);
2020-07-11 00:38:39 +02:00
return SUCCESS;
} catch (NumberFormatException e2) {
return FORMAT_ERROR;
}
} else if (split.length == 2) {
try {
Float.valueOf(split[0]); // min
Float.valueOf(split[1]); // max
return SUCCESS;
} catch (NumberFormatException e2) {
return FORMAT_ERROR;
}
} else {
return FORMAT_ERROR;
}
}
}
2020-10-24 16:58:27 +02:00
@NotNull
@Override
2020-10-24 16:58:27 +02:00
public FloatRange parse(@NotNull String value) {
if (value.contains("..")) {
2020-07-11 00:38:39 +02:00
final int index = value.indexOf('.');
final String[] split = value.split(Pattern.quote(".."));
2020-07-11 00:38:39 +02:00
final float min;
final float max;
if (index == 0) {
// Format ..NUMBER
min = Float.MIN_VALUE;
max = Float.parseFloat(split[0]);
2020-07-11 00:38:39 +02:00
} else {
if (split.length == 2) {
// Format NUMBER..NUMBER
min = Float.parseFloat(split[0]);
max = Float.parseFloat(split[1]);
2020-07-11 00:38:39 +02:00
} else {
// Format NUMBER..
min = Float.parseFloat(split[0]);
2020-07-11 00:38:39 +02:00
max = Float.MAX_VALUE;
}
}
return new FloatRange(min, max);
} else {
final float number = Float.parseFloat(value);
return new FloatRange(number);
}
}
}