java - URL data printing trouble -


i reading url = https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt

i trying print out top 3 countries whenever try gives me total number of countries instead. substring or trim method work here? need hint write direction. thanks

    class buttontotallistener implements actionlistener         {         public void actionperformed(actionevent event)         {                             if(event.getsource()==printbutton){            string line = "";            try{             string address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";             url pagelocation = new url(address);             scanner in = new scanner(pagelocation.openstream());             while(in.hasnextline()){             line = in.nextline();             string [] linecontent = line.split("\\s{2,}");             system.out.println(arrays.tostring(linecontent));             countries.setforeground(color.yellow);             countries.settext(linecontent[2]);             }             }                catch (malformedurlexception ex) {                   countries.settext("country not found!");               }                catch (ioexception ex) {}      } 

you loop on countries in in.hasnextline()

you should introduce counter variable , insert break; after limit reached, or change loop condition.

additionally check column want return. seems return number thrid column (which [2]), if want use country name need [1] 2nd column (array index 0-based).

as third, do countries? set text, each loop iteration, overwrite former countries text (countries same variable, in each iteration)


Comments