简体   繁体   English

在循环外部访问while循环创建的数组

[英]Accessing a while-loop created array outside of the loop

I am creating an array using a while loop. 我正在使用while循环创建一个数组。 (For reasons why I am creating an array this way, go to https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt ) Though once my array ( data ) is created inside the while loop, I cannot access it outside of the while loop. (出于我为什么要以这种方式创建数组的原因,请访问https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt )尽管一旦在内部创建了数组( data ) while循环,我无法在while循环之外访问它。 I was hoping to make it so the user could put in the name of a country, say India, and get the number of mobile users in that country. 我希望这样做,以便用户可以输入一个国家(例如印度)的名称,并获得该国家/地区的移动用户数量。

String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
URL pageLocation = new URL(address);
Scanner in1 = new Scanner(pageLocation.openStream());
Scanner in = new Scanner(System.in);
String line;
System.out.print("Please enter the name of the country you would like to see the mobile users for: ");
String country = in.next();
 while (in1.hasNextLine()){
 line = in1.nextLine();
 String[] data = line.split("\t");
 if (data[1].contains(country) == true){
   System.out.println("Country name: " + data[1]);
   System.out.println("Mobile phone subscribers: " + data[2]);
   return;
 } 
 else{
   System.out.println("No country found with that name!");
   return;
    }
  }

The input works if it is inside the loop, but will only work with China because it is the first country in the list. 如果输入在循环内,则输入有效,但仅与中国一起使用,因为它是列表中的第一个国家。 I understand why it is not working correctly, thought I'm unsure how to fix it other than putting the if statement outside of the loop, but if I do that, the statement cannot reach my array. 我理解为什么它不能正常工作,以为除了将if语句放在循环之外,我不确定如何解决它,但是如果我这样做,该语句将无法到达我的数组。 Any suggestions? 有什么建议么?

The issue is here : 问题在这里:

 if (data[1].contains(country) == true){
   System.out.println("Country name: " + data[1]);
   System.out.println("Mobile phone subscribers: " + data[2]);
   return;
 } else {
   System.out.println("No country found with that name!");
   return; //<-----ISSUE
 }

When return is called in your else clause it terminates the program. 在else子句中调用return ,它将终止程序。 What it really needs to do is iterate through the second run of the loop. 它真正需要做的是遍历循环的第二轮。

Remove the return in your else-statment . 在您的else-statment删除return

Here's the revised code: 这是修改后的代码:

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

public class TestClass {
    public static void main(String[] args) throws IOException {
        String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
        URL pageLocation = new URL(address);
        Scanner in1 = new Scanner(pageLocation.openStream());
        Scanner in = new Scanner(System.in);
        String line;
        System.out
                .print("Please enter the name of the country you would like to see the mobile users for: ");
        String country = in.next();

        while (in1.hasNextLine()) {
            line = in1.nextLine();
            String[] data = line.split("\t");

            if (data[1].contains(country) == true) {
                System.out.println("Country name: " + data[1]);
                System.out.println("Mobile phone subscribers: " + data[2]);
                return; //<--- will exit after printing ^
            }
        }
        System.out.println("No country found with that name!");
    }
}

Here's a sample run: {input} India 这是一个示例运行: {input} India

Please enter the name of the country you would like to see the mobile users for: India
Country name: India
Mobile phone subscribers:       893,862,000

You are not able to iterate to second line because you are returning the while after first iteration whether it found the country or not. 您无法迭代到第二行,因为无论是否找到该国家/地区,您都将在第一次迭代后返回一会儿。

I would suggest to remove the return statement from the else condition. 我建议从else条件中删除return语句。

I have also used a boolean variable found which will be set once the country is found and No country found message will be appear only if that country is not in list. 我还使用了一个boolean变量,该变量将在找到国家后设置,并且仅当该国家不在列表中时,才会出现“ No country found消息。

import java.io.IOException;
import java.net.URL;
import java.util.Scanner;

public class CountryName {
public static void main(final String[] args) throws IOException {
    final String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
    final URL pageLocation = new URL(address);
    final Scanner in1 = new Scanner(pageLocation.openStream());
    final Scanner in = new Scanner(System.in);
    boolean found = false;
    String line;
    System.out
            .print("Please enter the name of the country you would like to see the mobile users for: ");
    final String country = in.next();
    while (in1.hasNextLine()) {
        line = in1.nextLine();
        final String[] data = line.split("\t");
        if (data[1].contains(country) == true) {
            System.out.println("Country name: " + data[1]);
            System.out.println("Mobile phone subscribers: " + data[2]);
            found = true;
            return;
        }
    }
    if (!found) {
        System.out.println("No Country Found");
    }
in.close();
in1.close();
}

} }

On the other note, if you wants to use collections your program will become more concise and easy to read. 另一方面,如果您想使用集合,您的程序将变得更加简洁和易于阅读。 Here is the same logic with HashMap 这与HashMap逻辑相同

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CountryName {
    public static void main(final String[] args) throws IOException {
        final String address = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2151.txt";
        final URL pageLocation = new URL(address);
        final Scanner in1 = new Scanner(pageLocation.openStream());
        final Scanner in = new Scanner(System.in);
        final Map<String, String> countryMap = new HashMap<String, String>();
        while (in1.hasNextLine()) {
            final String[] line = in1.nextLine().split("\t");
            countryMap.put(line[1], line[2]);
        }
        System.out.print("Please enter the name of the country you would like to see the mobile users for: ");
        final String country = in.next();
        if (countryMap.containsKey(country)) {
            System.out.println("Country Name: " + country);
            System.out.println("Mobile phone subscribers: "+ countryMap.get(country));
        } else {
            System.out.println("No Country found with that name");
        }
        in.close();
        in1.close();
    }
}

Try putting 试穿

String[] data;

before your loop. 在循环之前。 That will make its scope greater than just the loop. 这将使它的作用范围不仅仅是循环。

Declare data outside "while" but assign it inside. 在“ while”之外声明数据,但在内部声明它。

String address = "https://www.cia.gov/library/publications/the-world-        factbook/rankorder/rawdata_2151.txt";
URL pageLocation = new URL(address);
Scanner in1 = new Scanner(pageLocation.openStream());
Scanner in = new Scanner(System.in);
String line;
System.out.print("Please enter the name of the country you would like to see the mobile users for: ");
String country = in.next();
String[] data; 
while (in1.hasNextLine()){
   line = in1.nextLine();
   data = line.split("\t");
   if (data[1].contains(country) == true){
     System.out.println("Country name: " + data[1]);
     System.out.println("Mobile phone subscribers: " + data[2]);
     return;
   } else{
   System.out.println("No country found with that name!");
   return;
   }
 }
Objects.toString(data); // now its visible

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM