Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java URL数据打印故障_Java_User Interface_Url - Fatal编程技术网

Java URL数据打印故障

Java URL数据打印故障,java,user-interface,url,Java,User Interface,Url,我正在从URL读取= 我试图打印出前三名的国家,但每当我尝试时,它都会给出答案 请告诉我国家总数。子字符串或修剪方法在这里有效吗?只需要一个写入方向的提示。谢谢 class ButtonTotalListener implements ActionListener { public void actionPerformed(ActionEvent event) { if(event.g

我正在从URL读取=

我试图打印出前三名的国家,但每当我尝试时,它都会给出答案 请告诉我国家总数。子字符串或修剪方法在这里有效吗?只需要一个写入方向的提示。谢谢

    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) {}
     }

您可以在in.hasNextLine()中遍历所有国家/地区

您应该引入一个计数器变量并插入一个中断;达到限制后,或更改循环条件

另外,请检查要返回的列。似乎是从第三列(即[2])返回数字,但如果要在第二列中使用国家名称,则需要[1](数组索引以0为基础)


第三,你对国家做了什么?您可以设置文本,但对于每个循环迭代,您都会覆盖以前的国家文本(国家是相同的变量,在每个迭代中)

使用一个变量来记录while循环进行了多少次迭代,并将while循环更改为以下
int count=0;而(count<3&&in.hasNextLine()){…;count+=1;}
。完成后,不要忘记关闭扫描仪。我还将
printStackTrace()
s您遇到的例外情况,如果您在开发过程中遇到错误,这将非常有用。我将国家附加到一个按钮,当按下该按钮时,将从URL打印前三个国家。我只是没有为此附加GUI代码。我感谢你的帮助,我的教授已经三天没有给我发电子邮件了。