2017-11-13 15 views
-6

여기에 두 가지 문제가 있습니다.누군가이 코드의 기능을 설명 할 수 있습니까

다음 코드 블록은 혼란 스럽습니다. 주로 코드가 기본에서 무엇을하는지 정확히 알지 못합니다. 방금 튜토리얼에서 복사했는데, 원하는대로 할 것 같습니다. 누군가가 비트로 설명 할 수 있다면 정말 도움이 될 것입니다.

두 번째 문제점은 ArrayIndexOutOfBounds 오류가 발생하는 이유를 모르겠다는 것입니다. 이유는 이해할 수 없기 때문일 수 있습니다. 정말 명확한 설명이 필요합니다.

try { 
     Document searchLink = Jsoup.connect("https://www.google.com.ng/search?dcr=0&source=hp&ei=5-cIWuZ30cCwB7aUhrAN&q=" + URLEncoder.encode(searchValue, encoding)) 
       .userAgent("Mozilla/5.0").get(); 
     String websiteLink = searchLink.getElementsByTag("cite").get(0).text(); 


     //we are setting the value for the action "titles" in the wikipedia API with our own article title 
     //we use the string method replaceAll() to remove the title of the article from the wikipedia URL that we generated from google 
     // 
     String wikiAPItoSearch = "https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles=" 
           + URLEncoder.encode(websiteLink.replaceAll("https://en.wikipedia.org/wiki/", ""),encoding); 
     System.out.println(wikiAPItoSearch); 

     //extraction of textfiles 
     //from this point till down i cant really grab what is happening 
     HttpURLConnection httpconn = (HttpURLConnection) new URL(wikiAPItoSearch).openConnection(); 
     httpconn.addRequestProperty("userAgent", "Mozilla/5.0"); 

     BufferedReader bf = new BufferedReader(new InputStreamReader(httpconn.getInputStream())); 

     //read line by line 
     String response = bf.lines().collect(Collectors.joining()); 
     bf.close(); 
     ///it returns ArrayIndexOutOfBounds here 
     String result = response.split("\"extract\":\"")[1]; 
     System.out.println(result); 
    } catch (IOException e) { 
     // TODO: handle exception 
     e.printStackTrace(); 
    } 
+0

응답 변수를 콘솔에 출력하고 실제로 추출한 내용이 있는지 확인하려고하지 마십시오 : ":" 'word – johnII

답변

1

나는 누군가가 당신을 위해 코드를 설명하는 데 시간이 걸릴 것이라고 생각하지 않습니다. 디버깅을 할 수있는 좋은 기회입니다.

ArrayIndexOutOfBoundsresponse.split("\"extract\":\"")[1]입니다. String response을 2 부분 이상으로 나눌 수 있다는 보장은 없습니다.

오류를 방지하려면 확인을 추가하십시오. 대신에 ... 사용

String result = response.split("\"extract\":\"")[1]; 

...

String[] parts = response.split("\"extract\":\""); 
    String result; 
    if (parts.length >= 2) { 
     result = parts[1]; 
    } else { 
     result = "Error..." + response; // a simple fallback 
    } 

이 얼마나 분할 작품 : 귀하의 경우 그래서

String input = "one,two,three"; 
String[] parts = input.split(","); 
System.out.println(parts[0]); // prints 'one' 
System.out.println(parst[2]); // prints 'three' 

, [1]은 두 번째 항목을 의미합니다 부품 배열. "\"extract \ ": \" "가 응답에 적어도 한 번 나타나야합니다. 그렇지 않으면 부품 배열에 하나의 항목 만 있고 두 번째 항목에 도달하려고하면 오류가 발생합니다 (이후 .split은 regexp 문자열을 받아 들여서 "\"extract \ ": \" "는 정규식 예약 문자를 포함하고 있기 때문에 모든 것이 까다로워집니다.

+0

else 블록이 실행되고 포맷되지 않은 문자열이 반환됩니다. 이것은 문자열이 2 미만으로 분할되었음을 의미합니다. 그렇다면 [1]의 배열 크기에 대한 outOfBounds가 ... –

+0

문자열이 2보다 작게 분할되었습니다. 즉, 액세스하려고하면 OutOfBoundsException이 발생합니다. 존재하지 않는 두 번째 부분 색인은 0부터 시작하므로 첫 번째 것은 [0]이고 두 번째 것은 [ – Adder

+0

업데이트 된 답변보기] – Stefan

0

OPPS ... 내가 API를 사용하여 내가 오류를 일으켰다는 것을 깨달았습니다. 위키 미디어에서 가져온 API는/extract/delimetre를 사용하지 않기 때문에 더 많은 클리너를 위해 다른 스택 오버 플로우 관련 기사를 확인했습니다. API 특히 API 응답의 delimetre로/extract /를 사용하는 API

https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles= 

이이 오류를 발생시키는 전 하나 :

이 내가 가진 새로운 API는

https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles= 

나는 오류가있는 프로세스를 이해하는 나의 무능력에 기인 한 생각 -dept .. 응답 주셔서 감사합니다.