0

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.

5
  • 1
    Instead of that giant if statement, you could just use URL[URL.length - 1] to get the last element of the array. Commented Mar 21, 2013 at 0:40
  • @Jeffrey I don't understand. Wouldn't I need a giant if statement using your method? Commented Mar 21, 2013 at 0:44
  • 1
    Why would you? The last accessible index in any Java array will be Array.length - 1. Commented Mar 21, 2013 at 0:46
  • This would be an excellent candidate for regular expressions. Commented Mar 21, 2013 at 0:48
  • @Jeffrey 's method works because if the length is 1, you assign output to URL[0]. if the length is 2, you assign output to URL[1]. So the index is always one less than the length of the array, so theOutput = URL[URL.length - 1]` is sufficient Commented Mar 21, 2013 at 0:48

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.