Reputation: 1484
I am trying to create a program that will read in a file, split that file into an array wherever there is an "/" and then have the variable "theOutput" set as the value of the index in the array. Trouble is, the index is always equal to null. Here is my code:
String theOutput = null;
String content = new Scanner(new File("URL.txt")).useDelimiter("\\Z").next();
theInput = content;
String[] URL = theInput.split("/");
System.out.println(theInput);
System.out.println(URL.length);
if (URL.length == 1) {
theOutput = URL[0];
if (URL.length == 3) {
theOutput = URL[2];
if (URL.length == 4) {
theOutput = URL[3];
if (URL.length == 5) {
theOutput = URL[4];
if (URL.length == 6) {
theOutput = URL[5];
}
}
}
An example of the data found in the file would be "coffee://localhost/brew" so it doesn't always use 5 indexes in the array.
Upvotes: 0
Views: 53
Reputation: 926
your if statements are nested in each other, so if(URL.length == 3)
will only run if the length of the URL is 1. So, you should do something like this:
if(URL.length == 1){
theOutput = URL[0];
}
if(URL.length == 2){
theOutput = URL[1]
}
//etc.
or, you can say theOutput = URL[URL.length-1]
to get the last element of the array.
Upvotes: 1