读取文件并将它们存储到Java中的2D对象数组中?

时间:2017-02-01 19:16:55

标签: java file object multidimensional-array

我有一个Java项目我想做(为了好玩),但我在这一步中苦苦挣扎。我有来自两个国家,美国和中国的城市,我无法阅读该文件。我正在尝试使用分隔符来分隔中国和美国的城市。

这是我的文本文件" Cities.txt"

  

旧金山9874343 543443 193838

     

洛杉矶3900000 52000 22000

     

巴尔的摩622104 34423 1234

     

Houston 2196000 45444 29393

     

纽约市8500000 54000 27000

     

费城1510000 654334 21343

     

波士顿6423344 345334 13443

     

芝加哥2719000 39000 19282

     

圣地亚哥1323343 432343 18374

     

达拉斯1258000 423343 17363 |

     北京21500000 32454 23454

     

杭州9018000 32343 192828

     

Shanghia 24500000 432345 23444

     

广州20800654 323455 298383

     

武汉10670000 54344 302344

     

Swatow 5391028 43345 23235

     

香港7234800 39039 278383

     

澳门650900 34543 17364

     

深圳10630000 44343 19883

     

淄博2980000 49383 20009

这是我的主要Java类。我还有一个带有构造函数,getter / setter和toString()的Cities类;

static Cities[][] multi = new Cities[2][10];



public static void main(String[] args) throws FileNotFoundException {
   System.out.println("The point of this program is to compare different cities in the two major superpower countries, \n The United States and China.");
System.out.println("The information in the cities in stored in a 2D array of Objects and is pre-created in a text files. \n Please pick an option to manipulate the information in the array.");
Scanner in = new Scanner(System.in); 
String name = " "; 
int population = 0; 
double wage = 0.0;
int density = 0;
Cities cities = new Cities(name,population,wage,density); 

boolean exit = false; 
readcity(name);
String options = "1). Print all the cities. \n 2). Print just the united states cities. \n 3). Print just the China Cities \n 90). Exit program";
System.out.println(options);
int decide = in.nextInt();
while (!exit)
{
    switch (decide) {
        case 1:
        {
            printarray(name,population,wage,density);
        }
        case 2: {

        }
        case 3: {

        }

        case 90: {
            exit = true; 

        }
}

}
}


public static Cities readcity(String fline)
{
try {
  String name; int population; double wage; int density;        
    int countries = 2; int city = 10;   
     Scanner fileScan = new Scanner(new File("/src/Cities.txt"));
   fileScan.useDelimiter("|"); 
    while (fileScan.hasNext()) {
      name = fileScan.next();
      population = fileScan.nextInt();
      wage = fileScan.nextDouble(); 
      density = fileScan.nextInt();
     Cities City = new Cities(name, population, wage, density);
     return new Cities(name,population,wage,density);

    }




 fileScan.nextLine();   
Cities City = readcity(fline);
multi[countries][city] = City; 
return City;
  }
  catch(Exception e) {
   System.out.println("Looks like there was an error.");
  }
  Cities City = readcity(fline);
  return City;
  }
 public static void printarray(String name, int population, double wage, int density) throws FileNotFoundException{


 Cities cities = new Cities(name,population,wage,density); 

                   for (int row =0; row < multi.length; row++){
                       for (int column = 0; column < multi[row].length; column++){
                           System.out.println(multi[row][column]);
                       }
                       System.out.println();
                   }
                   cities.toString(); 
   }
   }

该方法似乎正在进行无限递归调用,但我想知道如何解决这个问题。我会为两个文件执行相同的方法并实现这种方式吗?或者我会把他们的方法带到城市阅读并通过不同的方法实施它们?我对文件处理很弱,使用二维数组甚至是一个更高的层。试图解决我的弱点,以便你能给我的任何帮助都是有益的。

2 个答案:

答案 0 :(得分:0)

那么,我从哪里开始......

  1. 您的readcity()方法以递归方式调用自身。我认为这不是主意。尝试删除这些电话。
  2. 您对readcity()的初始调用是使用参数“”。不知道这里有什么用意。
  3. 在“while(fileScan.hasNext())之后打开括号”{“显然在上面的代码中丢失了。
  4. 通常,尝试根据多个类命名您的类和变量。如果一个对象应该占有一个城市,那么它的类应该被称为“城市”。如果一个对象应该包含一组城市,那么你可以调用“城市”这个类。

答案 1 :(得分:0)

在这种情况下无需递归来读取文件。我绝对建议写评论,以便外部用户基本知道一切都在做什么。嗯。我也会更容易从文件中获取数据,因为你没有太多关于我假设的文件处理经验吗?。

我重新格式化了文件,以便在某种意义上使事情变得更容易。这样你就可以通过使用split来获取','之间的每个信息。

US:
San Francisco, 9874343, 543443, 193838
Los Angeles, 3900000, 52000, 22000
Baltimore, 622104, 34423, 1234
Houston, 2196000, 45444, 29393
New York City, 8500000, 54000, 27000
Philadelphia, 1510000, 654334, 21343
Boston, 6423344, 345334, 13443
Chicago, 2719000, 39000, 19282
San Diego, 1323343, 432343, 18374
Dallas, 1258000, 423343, 17363
China:
Beijing, 21500000, 32454, 23454
Hangzhouu, 9018000, 32343, 192828
Shanghia, 24500000, 432345, 23444
GuangZhou, 20800654, 323455, 298383
Wuhan, 10670000, 54344, 302344
Swatow, 5391028, 43345, 23235
Hong Kong, 7234800, 39039, 278383
Macau, 650900, 34543, 17364
Shenzhen, 10630000, 44343, 19883
Zibo, 2980000, 49383, 20009

这是我读取数据并存储在二维城市数组中的类。

public class CityReader {


    public static void main(String[] args)
    {

        City[][] cities = new City[2][10];
        readFileInto2D("src/Cities.txt",cities);
        //User prompt on what they want to here?    
        print2DArray(cities);
    }

    public static void readFileInto2D(String filename,City[][] cities)
    {
        City city;
        String name = "";
        int population = 0;
        int wage = 0;
        int density = 0;

        try {

            Scanner scan = new Scanner(new File(filename));

            String line;
            String[] parsed;

            //Read US:
            if(scan.hasNext())
                line = scan.nextLine();

            //Keep track of rows
            int indexer = 0; 
            //Keep track of columns
            int indexer2 = 0;

            while(scan.hasNext())
            {
                line = scan.nextLine();

                if(line.contains("China"))
                {
                    indexer += 1;//Go to next row
                    indexer2 = 0;//Start index at beginning of column.
                    line = scan.nextLine();//Read next line, ignore line with China.
                }
                parsed = line.split(", "); //This splits each line 
                                           //into an array of name,pop,wage,and density
                name = parsed[0];
                population = Integer.parseInt(parsed[1]);
                wage = Integer.parseInt(parsed[2]);
                density = Integer.parseInt(parsed[3]);              
                city = new City(name,population,wage,density);              
                cities[indexer][indexer2] = city;//Add to 2D Array.             
                indexer2++;                             
            }


        } catch (IOException ioe) {
            // TODO Auto-generated catch block
            ioe.printStackTrace();
        }



    }

    public static void print2DArray(City[][] cities)
    {
        //row
        for(int i = 0; i < cities.length; i++)
        {
            //column
            for(int j = 0; j < cities[i].length;j++)
            {
                City city = cities[i][j];
                //used getters to print information.
                System.out.printf("%s %d %d %d\n",city.getName(),
                        city.getPopulation(),city.getWage(),
                        city.getDensity());
            }
            System.out.println();
        }
    }
}

现在这并不完美,用户可以轻松实现错误,因为没有错误检查。这更像是展示一种方法。使用的城市类是基本的,只有构造函数和getter和setter。