微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将字符串数组扫描和处理为另一个没有重复的多维数组?

如何解决如何将字符串数组扫描和处理为另一个没有重复的多维数组?

| 抱歉,标题有点混乱。我需要做的是读取一个文本文件,其中包含许多城市和州,它们位于不同的行,如下所示:
Salem,Oregon
St. George,Utah
Augusta,Maine
Portland,Maine
Jefferson City,Missouri
Kansas City,Missouri
Portland,Oregon
Salt Lake City,Utah
然后从这样的输出
Maine: Augusta,Portland
Missouri: Jefferson City,Kansas City
Oregon: Portland,Salem
Utah: Salt Lake City,St. George
我必须用一种方法完成它,然后将其发送到多维数组或arraylist中,其中第一维将是州,第二维将是对应的城市。 我以为最简单的方法是为每个城市和州制作分类令牌,但是我不知道随后如何对它们进行正确分类。我已经创建了令牌,然后将它们重新打印到单独的行上,这是没有用的。 这是我当前的代码
import java.io.File;
import java.util.Scanner;
import java.util.Formatter;
import java.io.FileNotFoundException;
import java.util.Arrays;

public class munge
{

    private String inFileName,outFileName;
    private Scanner inFile;
    private Formatter outFile;
    private int line = 0;

    private String[] data;

    public munge(String inFileName,String outFileName)
    {
        this.inFileName = inFileName;
        this.outFileName = outFileName;

        data = new String[100];
    }

    public void openFiles()
    {
        try
        {
            inFile = new Scanner(new File(inFileName));
        }
        catch(FileNotFoundException exception)
        {
            System.err.println(\"File not found.\");
            System.exit(1);
        }
        catch(SecurityException exception)
        {
            System.err.println(\"You do not have access to this file.\");
            System.exit(1);
        }

        try
        {
            outFile = new Formatter(outFileName);
        }
        catch(FileNotFoundException exception)
        {
            System.err.println(\"File not found.\");
            System.exit(1);
        }
        catch(SecurityException exception)
        {
            System.err.println(\"You do not have access to this file.\");
            System.exit(1);
        }
    }

    public void readRecords()
    {
        while(inFile.hasNext())
        {
            data[line] = inFile.nextLine();
            System.out.println(data[line]);
            line++;
        }
    }

    public void writeRecords()
    {
        for(int i = 0; i < line; i++)
        {
            String tokens[] = data[i].split(\",\");
            Arrays.sort(tokens);

            for(int j = 0; j < tokens.length; j++)
                outFile.format(\"%s\\r\\n\",tokens[j]);
        }
    }

    public void closeFiles()
    {
        if(inFile != null)
            inFile.close();

        if(outFile != null)
            outFile.close();
    }
}
我真的不知道我在做什么,而且我对Java和任何编程的理解都非常有限。我到这里来已经有好几个小时了。如果有人可以帮助我,我将非常感激。     

解决方法

这是一些带有注释的代码,希望对您有所帮助:
// your input file with city,state values
File file = new File(\"states.txt\");

// data structure to hold mapping of state to list of cities,sorted by state
SortedMap<String,List<String>> map = new TreeMap<String,List<String>>();

// scan file by line and populate data structure
Scanner scanner = new Scanner(file).useDelimiter(\"\\\\n\");
while (scanner.hasNext()) {
    String line = scanner.next();

    // only process lines with a comma
    if (line.contains(\",\")) {
        // split the line on the comma and extract the city and state
        // note this won\'t work properly if the city has a comma in it
        String[] parts = line.split(\",\");
        String city = parts[0].trim();
        String state = parts[1].trim();

        // if the state doesn\'t exist in the map yet,create it
        List<String> cities = map.get(state);
        if (cities == null) {
            cities = new ArrayList<String>();
            map.put(state,cities);
        }

        // add the city to the list for the state if it\'s not in it yet
        if (!cities.contains(city)) {
            cities.add(city);
        }
    }
}

// iterate over the states for output
for (String state : map.keySet()) {
    // build up a string for each state with the list of cities
    StringBuilder sb = new StringBuilder();

    // start with the state
    sb.append(state + \": \");

    // now append the cities
    List<String> cities = map.get(state);
    for (String city : cities) {
        sb.append(city + \",\");
    }

    // remove the last comma
    sb.delete(sb.length() - 2,sb.length());

    // print out the finished line
    String output = sb.toString();
    System.out.println(output);
}
    ,您需要具有每个州的城市列表。 因此,您将得到类似于
Map<String,List<String>>
的信息,并且在解析(即拆分)您的输入后,您会为您的州查找正确的列表并放入城市。 最后,您遍历地图以正确的顺序打印出所有内容。     ,我建议使用将每个州名称映射到城市名称的ArrayList的HashMap。处理每个输入记录时,请从HashMap中检索该状态的ArrayList。如果不存在,则这是该状态的第一条记录,因此创建一个新的ArrayList并将其放在状态名称下的HashMap中。假设任何特定的城市/州对仅出现一次,则无需检查重复项。如果最后需要将其作为多维数组,则可以在处理完所有内容后从HashMap中提取所有键/值对。     ,尝试使用哈希表(状态名称作为键)来解决此问题。 默认情况下,在“哈希冲突”(状态-城市对已经存在)的情况下,一个键的存储桶存储多个条目,可以使用HashTable Java api顺序搜索这些条目。最后,您将获得一个数据结构,您可以在其中访问以州为键的城市。 或者,您可以将状态名称用作键,并将数组列表存储为值。如果给出了一个状态,则没有任何关联的值,创建一个新的ArrayList,向其添加城市,然后将ArrayList成对存储在HashTable中。如果指定了状态,则ArrayList作为值已经存在,检索ArrayList并插入您的城市。 :) 您可以在Java 6 API中查找数据结构。 哈希表     ,使用HashMap或ArrayList进行代码。 HashMap的键表示状态,ArrayList将包含城市。 免责声明:我在记事本中键入了代码,因此可能存在编译错误。但是你明白了。
/*
Store each State as a key in the HashMap.
For each State assign an arraylist of cities.
We use StringTokenizer to split the state and the city.
*/
HashMap<String,ArrayList<String>> hmStateCity = new  HashMap<String,ArrayList<String>>();

public void readRecords()
{
      while(inFile.hasNext())
     {
       String sInputLine = inFile.nextLine();
       StringTokenizer stInput = new StringTokenizer(sInputLine,\",true);
       int i = 0; //when i is 0 = State,1 = city
    ArrayList<String> arrCity = new ArrayList<String>();
       while (stInput.hasMoreElements()) 
       {
          String sToken = stInput.nextElement();
          if( i == 0)
          {
               arrCity = hmStateCity.get( sToken );
               if(arrCity  == null)
               {    // this indicates that this particular State was never created.
                    // so assign a new ArrayList to the State. 
            arrCity = new ArrayList<String>();
            hmStateCity.put( token,arrCity );
               }
          }
          else if( i == 1 )
          {
               arrCity.add( sToken );
          }

          i++;
       }
     }
}

/* Iterate through HashMAp. The Map\'s key is the State name.
Retrieve the List of cities using the \"State\".
The String sStateCityLine  will have each line that can be written one at a time.
*/

public void writeRecords()
{
    if(hmStateCity !=null)
    {
        Set<String> setStateName = hmStateCity.keySet();

        for(String sState : setStateName )
        {
            String sStateCityLine = sState + \":\" ;
            ArrayList<String> arrCity = hmStateCity.get( sState );
            if( arrCity!=null && !arrCity.isEmpty() )
            {
                boolean isFirstCity = true;
                for(String sCity : arrCity )
                {
                    if( !isFirstCity )
                    {
                        sStateCityLine  = sStateCityLine  + \",\";
                    }
                    sStateCityLine  = sStateCityLine  + \" \" + sCity;
                    isFirstCity = false;
                }
            }

            //Insert code here to write the String sStateCityLine line by line
        }
    }
}
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。