-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArgumentParser.java
More file actions
106 lines (91 loc) · 2.25 KB
/
Copy pathArgumentParser.java
File metadata and controls
106 lines (91 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/* Author: Edric Orense
* File: ArgumentParser.java
* Purpose: Parse arguments sent from the command-line
*/
import java.util.HashMap;
public class ArgumentParser {
private String[] args;
private HashMap<String, String> flagMap;
public ArgumentParser(String[] args) {
flagMap = new HashMap<String, String>();
this.args = args;
if (args.length == 0) {
System.out.println("No arguments entered");
System.exit(0);
}
// adds the arguments to the hash map when the argument parser gets
// initialized.
for (int i = 0; i < args.length; i++) {
addToMap(args[i]);
}
}
// adds the flag given and the associated value into a hash map.
// if the flag has no value associated with it, a blank is set as its value.
public void addToMap(String flag) {
if (flag.startsWith("-")) {
if (hasFlag(flag)) {
if (hasValue(flag)) {
this.flagMap.put(flag, getValue(flag));
} else {
this.flagMap.put(flag, "");
}
}
}
}
// check if the flag given as a parameter can be found as an argument.
public boolean hasFlag(String flag) {
for (int i = 0; i < args.length; i++) {
if (flag.equals(args[i])) {
return true;
}
}
return false;
}
// checks if there is a value associated with the given flag.
public boolean hasValue(String flag) {
for (int i = 0; i < args.length; i++) {
if (flag.equals(args[i])) {
if (i < args.length - 1) {
if (!args[i + 1].startsWith("-")) {
return true;
}
}
}
}
return false;
}
// gets the value for the given flag
public String getValue(String flag) {
String value = "";
if (hasValue(flag)) {
for (int i = 0; i < args.length; i++) {
if (flag.equals(args[i])) {
value = args[i + 1];
}
}
}
return value;
}
// counts the number of flags given.
public int numFlags() {
int flagCount = 0;
for (String s : this.args) {
if (s.startsWith("-")) {
flagCount++;
}
}
return flagCount;
}
// counts the number of arguments given.
public int numArguments() {
int argCount = 0;
for (String s : this.args) {
if (s.startsWith("-")) {
if (hasValue(s)) {
argCount++;
}
}
}
return argCount;
}
}