Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.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 如何在没有重复项的情况下将字符串数组扫描并操纵到不同的多维数组中?_Java_Arrays_Arraylist - Fatal编程技术网

Java 如何在没有重复项的情况下将字符串数组扫描并操纵到不同的多维数组中?

Java 如何在没有重复项的情况下将字符串数组扫描并操纵到不同的多维数组中?,java,arrays,arraylist,Java,Arrays,Arraylist,抱歉,标题有点混乱。我需要做的是读取一个文本文件,其中包含一系列城市和州,它们分别位于以下行: 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, Kan

抱歉,标题有点混乱。我需要做的是读取一个文本文件,其中包含一系列城市和州,它们分别位于以下行:

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
然后将其输出如下:

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
我必须用一个方法完成,然后发送到多维数组或数组列表中,其中第一个维度是州,第二个维度是相应的城市

我认为最简单的方法是为每个城市和州制作一种代币,但我不知道以后如何正确地对它们进行分类。我已经创建了令牌,然后将它们重新打印到单独的行上,这是毫无用处的

这是我目前的代码:

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.io.File;
导入java.util.Scanner;
导入java.util.Formatter;
导入java.io.FileNotFoundException;
导入java.util.array;
公共课堂语言
{
私有字符串填充名,outFileName;
私人扫描仪填充;
专用格式化程序输出文件;
私有整数行=0;
私有字符串[]数据;
公共语言(字符串填充名、字符串输出名)
{
this.inFileName=inFileName;
this.outFileName=outFileName;
数据=新字符串[100];
}
公共void openFiles()
{
尝试
{
inFile=新扫描仪(新文件(inFileName));
}
捕获(FileNotFoundException异常)
{
System.err.println(“未找到文件”);
系统出口(1);
}
捕获(SecurityException异常)
{
System.err.println(“您无权访问此文件”);
系统出口(1);
}
尝试
{
outFile=新格式化程序(outFileName);
}
捕获(FileNotFoundException异常)
{
System.err.println(“未找到文件”);
系统出口(1);
}
捕获(SecurityException异常)
{
System.err.println(“您无权访问此文件”);
系统出口(1);
}
}
公共档案
{
while(infle.hasNext())
{
data[line]=infle.nextLine();
System.out.println(数据[行]);
line++;
}
}
公共无效书面记录()
{
对于(int i=0;i

我真的不知道我在做什么,我对Java和任何编程的理解都非常有限。我已经这样做了好几个小时了。如果有人能帮助我,我将非常感激。

你需要每个州的城市列表

因此,您将拥有类似于
Map
,并且在解析(即拆分)您的输入后,您将查找您所在州的正确列表并将其放入城市


最后,您将遍历地图,以正确的顺序打印所有内容。

我建议使用HashMap,将每个州的名称映射到城市名称的数组列表。在处理每个输入记录时,从HashMap中检索状态的ArrayList。如果不存在,那么这是状态的第一条记录,因此创建一个新的ArrayList并将其放在状态名称下的HashMap中。假设任何特定的城市/州对只出现一次,则无需检查重复项。如果最后需要将其作为多维数组,则可以在处理完所有内容后从HashMap中提取所有键/值对。

尝试使用哈希表,使用状态名称作为键来解决此问题

默认情况下,在发生“哈希冲突”(州-市对已经存在)的情况下,一个密钥的单个bucket存储多个条目,可以使用哈希表javaapi顺序搜索这些条目。最后,您将得到一个数据结构,在该结构中,您可以访问给定状态作为密钥的城市

或者,您可以使用状态名称作为键,并将数组列表存储为值。如果给定一个状态,则没有与之关联的值,创建一个新的ArrayList,将您的城市添加到其中,然后将ArrayList成对存储在哈希表中。如果给定状态,ArrayList已作为值存在,请检索ArrayList并插入您的城市。:)

您可以在Java6API中查找数据结构


以下是一些代码和注释,希望对您有所帮助:

// 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);
}
//使用城市、州值输入文件
File File=新文件(“states.txt”);
//保存州到城市列表映射的数据结构,按州排序
SortedMap map=新树映射();
//逐行扫描文件并填充数据结构
Scanner Scanner=新的扫描仪(文件).useDelimiter(\\n”);
while(scanner.hasNext()){
字符串行=scanner.next();
//仅处理带有逗号的行
if(第行包含(“,”){
//在逗号处拆分行,并提取城市和州
//请注意,如果城市中有逗号,则无法正常工作
String[]parts=line.split(“,”);
字符串city=parts[0]。trim();
字符串状态=零件[1]。修剪();
//如果地图中还不存在该状态,请创建它
List cities=map.get(state);
如果(城市==null){
城市=新阵列列表();
地图。放置(州、城市);
}
//将城市添加到该州的列表中(如果它还不在列表中)
如果(!cities.contains(城市)){
城市。添加(城市);
}
}
}
//迭代状态以获得输出
for(字符串状态:map.keySet()){
//为每个sta建立一个字符串