38public final class CommandParser {
40 private final String command;
41 private final String[] arguments;
45 private CommandParser(String command, String input, String splitter) {
46 this.command = command;
47 this.arguments = Arrays.stream(input.split(splitter)).toArray(String[]::new);
50 public static CommandParser split(CommandParser parser, String splitter) {
51 return new CommandParser(parser.getCommand(), parser.nextLine(), splitter);
54 public static CommandParser split(String input, String splitter) {
55 final int index = input.indexOf(splitter);
57 final String command = index == -1 ? input : input.substring(0, index);
59 return split(command, input, splitter);
62 public static CommandParser split(String command, String input, String splitter) {
64 int position = input.indexOf(command);
70 final String
string = input.substring(position + command.length()).trim();
72 return new CommandParser(command,
string, splitter);
75 public String getCommand() {
79 public boolean hasNext() {
80 if (arguments.length == 1) {
81 if (arguments[0].isEmpty()) {
88 public boolean hasNext(
int length) {
89 return pointer + length <= arguments.length;
92 public boolean nextBoolean() {
93 return Boolean.parseBoolean(nextString());
96 public byte nextByte()
throws NumberFormatException {
97 return Byte.parseByte(nextString());
100 public double nextDouble()
throws NumberFormatException {
101 return Double.parseDouble(nextString());
104 public int nextInt()
throws NumberFormatException {
105 return Integer.parseInt(nextString());
108 public long nextLong()
throws NumberFormatException {
109 return Long.parseLong(nextString());
112 public short nextShort()
throws NumberFormatException {
113 return Short.parseShort(nextString());
116 public String nextString()
throws ArrayIndexOutOfBoundsException {
117 if (pointer >= arguments.length) {
118 throw new ArrayIndexOutOfBoundsException(
"The next argument does not exist. [Size: " + arguments.length +
", Attempted: " + pointer +
"]");
121 return arguments[pointer++];
124 public String nextLine() {
125 final StringBuilder builder =
new StringBuilder();
128 builder.append(
" ").append(nextString());
130 return builder.toString().trim();
133 public int argumentCount() {
134 return arguments.length;
137 public String[] getArguments() {
142 public String toString() {
143 return String.format(
"command=[%s] arguments=%s", command, arguments ==
null ?
"none" : Arrays.toString(arguments));