Checking Valid URL

258 views Asked by At

I have a built in check for a valid URL.. I have inserted the portion of my check. The program is to read a ranked list and then print/sort/search. The first portion of code is my check for valid URL, the second portion is inserting it to an arrayList. If I enter the url: https://www.ssa.gov/cgi-bin/popularnames.cgi I get the following error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at rankings.RankMenu.toArrayList(RankMenu.java:160)
at rankings.RankMenu.menu(RankMenu.java:84)
at rankings.Rankings.main(Rankings.java:16)
Java Result: 1

Line 160 is:

String test2 = temp[element];

The code to pass string toArrayList is:

Scanner read = new Scanner(text.openStream());
while(count < 25){
output = read.nextLine();

How can I check the URL to prevent this OR adjust my code that inserts a file into the arrayList? This total project 223 lines of code in just the menu so I will pass on posting it all unless needed for help. Thank you.

public boolean isValidURL(String url){
    try{
        java.net.URL file = new java.net.URL(url);
        this.text = file;
        return true;
    } catch (java.net.MalformedURLException ex) {
        return false;
    } catch (java.io.IOException ex){
        return false;
    }
}  

public void toArrayList(String string, int rank, int element){
    String[] temp = string.split("\\s+");
    String test = temp[rank];
    String test2 = temp[element];
    String[] newTemp = new String[temp.length - 2];
    int cnt2 = 0;
    for(int cnt = 0; cnt < temp.length; cnt++){
        if(temp[cnt] != temp[rank] && temp[cnt] != temp[element]){ 
            newTemp[cnt2] = temp[cnt];
            cnt2++;
        }            
    }
    String test3 = Arrays.toString(newTemp);
    textList.add(new Type(test, test2, test3));
}
1

There are 1 answers

1
Atri On

Check rank, element are less than length of temp array before accessing it using temp[rank] and temp[element].

Also, check if cnt2 ever goes beyond the length of newTemp.