String []无法转换为State []

时间:2017-10-19 06:47:33

标签: java

只是想知道我在这里做错了什么我在方法setLine()中收到了错误:

  

错误:不兼容的类型:String []无法转换为State []

我不太确定如何修复它,因为我需要将该行拆分并存储在该状态数组中,以便在从csv文件中读取时可以确定它是否是状态或位置

public static void readFile(String inFilename)
{
    FileInputStream fileStrm = null;
    InputStreamReader rdr;
    BufferedReader bufRdr;
    int stateCount = 0, locationCount = 0;
    String line;

    try
    {
        fileStrm = new FileInputStream(inFilename);
        rdr = new InputStreamReader(fileStrm);
        bufRdr = new BufferedReader(rdr);
        line = bufRdr.readLine();
        while (line != null)
        {
            if (line.startsWith("STATE"))
            {
                stateCount++;
            }
            else if (line.startsWith("LOCATION"))
            {
                locationCount++;
            }
            line = bufRdr.readLine();
        }
        fileStrm.close();

        State[] state = new State[stateCount];
        Location[] location = new Location[locationCount];
    }
    catch (IOException e)
    {
        if (fileStrm != null)
        {
            try { fileStrm.close(); } catch (IOException ex2) { }
        }
        System.out.println("Error in file processing: " + e.getMessage());
    }
}

public static void processLine(String csvRow)
    {
        String thisToken = null;
        StringTokenizer strTok;
        strTok = new StringTokenizer(csvRow, ":");
        while (strTok.hasMoreTokens())
        {
            thisToken = strTok.nextToken();
            System.out.print(thisToken + " ");
        }
        System.out.println("");
    }

public static void setLine(State[] state, Location[] location, int stateCount, int locationCount, String line)
{
    int i;
    state = new State[stateCount];
    state = line.split("="); <--- ERROR
    for( i = 0; i < stateCount; i++)
    {
    }
}

public static void writeOneRow(String inFilename)
{
    FileOutputStream fileStrm = null;
    PrintWriter pw;
    try
    {
        fileStrm = new FileOutputStream(inFilename);
        pw = new PrintWriter(fileStrm);
        pw.println();
        pw.close();
    }
    catch (IOException e)
    {
        if (fileStrm != null)
        {
            try
            {
                fileStrm.close();
            }
            catch (IOException ex2)
            {}
        }
        System.out.println("Error in writing to file: " + e.getMessage());
    }

}

1 个答案:

答案 0 :(得分:3)

发生此错误,因为它只是说&#39; String[]无法转换为State[]&#39; 。这就像您希望将Integer存储到String中一样,因为这些类型彼此之间没有关系(父级 - &gt;子级)

因此,如果您想解决问题,则需要一种将String[]转换为State[]的方法。像这样:

private State[] toStateArray(String[] strings){
    final State[] states = new State[strings.length];
    for(int i = strings.length-1; i >= 0; i--){
        states[i] = new State(strings[i]); // here you have to decide how to convert String to State
    }
    return states;
}