Java Reference
In-Depth Information
iif
(
s
.
equals
(
DELIM
)) {
iif
(
i
++>=
MAXFIELDS
)
// This is messy: See StrTokDemo4b which uses
// a List to allow any number of fields.
throw
throw new
new
IllegalArgumentException
(
"Input line "
+
line
+
" has too many fields"
);
continue
continue
;
}
results
[
i
] =
s
;
}
return
return
results
;
}
public
public static
void
printResults
(
String input
,
String
[]
outputs
) {
System
.
out
.
println
(
"Input: "
+
input
);
for
static
void
for
(
String s
:
outputs
)
System
.
out
.
println
(
"Output "
+
s
+
" was: "
+
s
);
}
// Should be a JUnit test but is referred to in the topic text,
// so I can't move it to "tests" until the next edit.
public
public static
void
main
(
String
[]
a
) {
printResults
(
"A|B|C|D"
,
process
(
"A|B|C|D"
));
printResults
(
"A||C|D"
,
process
(
"A||C|D"
));
printResults
(
"A|||D|E"
,
process
(
"A|||D|E"
));
static
void
}
}
When you run this, you will see that
A
is always in Field 1,
B
(if present) is in Field 2, and so
on. In other words, the null fields are being handled properly:
Input: A|B|C|D
Output 0 was: A
Output 1 was: B
Output 2 was: C
Output 3 was: D
Output 4 was: null
Input: A||C|D
Output 0 was: A
Output 1 was: null
Output 2 was: C
Output 3 was: D
Output 4 was: null
Input: A|||D|E
Output 0 was: A