首页 > 解决方案 > 如何使用数组创建有组织的组?

问题描述

我在另一个洞里,我需要能够通过使用数组作为组来打印包含城市人口的文本文件。这些组包括:NA(未列出人口)、5000-7499、7500-9999 和 10,000-infinity。人口存储在一个文本文件中,如下所示。我也有我用来打印人口从最大到最小的当前代码,不包括将 Na 分组。

最后,我需要一个可以使用数组将文本文件组织成组的程序。但是,我仍然不知道如何处理数组。任何帮助将不胜感激。如果我不清楚任何事情或没有意义的事情,请随时提出问题......我对编程还是很陌生。谢谢你!!!

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Population {

public static void main(String[] args) throws IOException {
// TODO code application logic here

// // read KeyWestTemp.txt

// create token1
String token1 = "";


// create Scanner inFile1
Scanner inFile1 = new Scanner(new File("Populationtxt")).useDelimiter(",\\s*");

// Original answer used LinkedList, but probably preferable to use ArrayList in most cases
// List<String> temps = new LinkedList<String>();
List<String> temps = new ArrayList<String>();

// while loop
while (inFile1.hasNext()) {
  // find next line
  token1 = inFile1.next();
  temps.add(token1);
}
inFile1.close();

String[] tempsArray = temps.toArray(new String[0]);

for (String s : tempsArray) {
  System.out.println(s);


  }
  }
  }

以下是文本文件中列出的信息:

Philadelphia city:, 1526006

Pittsburgh city:,       305704

Harrisburg city:,       49528

Altoona city:,          46320

State College borough:, 42034

Monroeville municipality:, NA

Johnstown city:,        20978

Murrysville municipality:,20079

McKeesport city:,   NA

Greensburg city:,           14892

Indiana borough:,         13975

Washington city:,         13663

Meadville city:, NA

New Kensington city:,   13116

St. Marys city:,        13070

Lower Burrell city:,    11761

Munhall borough:,   NA

Jefferson Hills borough:,   10619

Waynesboro borough:,    10568

Oil City city:,         10557

Uniontown city:,        10372

Lock Haven city:,       9772

Jeannette city:,        9654

Beaver Falls city:, NA

Swissvale borough:, 8983

Mechanicsburg borough:, 8981

Carbondale city:,   NA

Latrobe city:,          8338

Grove City borough:,    8322

Pleasant Hills borough:,    8268

White Oak borough:, NA

DuBois city:,           7794

Monessen city:,         7720

Connellsville city:,    7637

Gettysburg borough:,    7620

California borough:,    6795

Somerset borough:,  6277

Clearfield borough:,    NA

McKees Rocks borough:,  6104

Punxsutawney borough:,  5962

Duquesne city:,         5565

Shippensburg borough:,  5492

Fox Chapel borough:,    5388

Turtle Creek borough:,  5349

Clarion borough:,         5276

Vandergrift borough:,   NA

Westmont borough:,  5181

Arnold city:,   NA

Kutztown borough:,  5012

标签: javaarrays

解决方案


要解决这个问题,您必须对数据进行排序。我将假设您不想重新排序文本文件,但添加起来并不难。因此,对数据进行排序的方法是找到一个简单的算法。如果您有时间,我建议您详细了解更大和更复杂的排序算法,但首先您可以使用简单的算法。您需要做的是抓住数字或字符并找到值。然后将其添加到数组中,最后对数组中的所有数据进行排序。Character.isDigit(string); 然后如果它是真的将它添加到数组中以获得一个数字。之后,您可以使用简单的排序算法(如冒泡排序)将数字按顺序排列,然后打印出在 for 循环中完成的列表,其中城市名称位于单独的数组中。


推荐阅读