如何从try / catch块中获取数组?

时间:2012-06-11 04:15:05

标签: java arrays try-catch

我一直在踢这段代码一段时间,我想我知道一般问题是什么,我无法弄清楚如何纠正它。我收到以下错误:

C:\Documents and Settings\Joe King\My Documents\418.85A Java\Project5>javac Project5.java
Project5.java:408: error: variable boatNames might not have been initialized
            boatArray1 = new Boat[boatNames.length];
                                  ^
1 error

问题是我的boatNames数组在try / catch块中,我认为这是将它与其余代码隔离开来。如何从try / catch块中取出boatNames数组?

我的代码如下:

class Project5{

public static void main(String[] args){

    String[] boatNames;
    Boat[] boatArray1;
    Boat[] boatArray2;
    String result = " "; 
    String name = null;
    char firstChar;
    char firstLetter;
    char secondLetter;
    int totalRead;
    int i;
    int j;
    int k;
    int l;
    int m;

    Path inPath = Paths.get("C:/Documents and Settings/Joe King/My Documents/418.85A Java/Projects/Input").resolve("Boat Names.txt");

    if(!Files.exists(inPath)){

        System.out.println(inPath + " does not exist.  Terminating the program.");
        System.exit(1);

    }

    try(BufferedReader fileIn = Files.newBufferedReader(inPath, Charset.forName("UTF-16"))){

        totalRead = 0;

        while(fileIn.readLine() != null){

            name = fileIn.readLine();
            ++totalRead;
            name = null;

        }

        boatNames = new String[totalRead];

        for(i = 0 ; i < boatNames.length ; ++i){

            name = fileIn.readLine();
            boatNames[i] = name;
            name = null;

        }

    }catch(IOException e){

        System.err.println("Error writing file: " + inPath);
        e.printStackTrace();

    }   

    Path outPath = Paths.get("C:/Documents and Settings/Joe King/My Documents/418.85A Java/Projects/Output").resolve("Fleet Registry.txt");

    try{

        Files.createDirectories(outPath.getParent());

    }catch(IOException e){

        System.err.println("Error creating directory: " + outPath.getParent());
        e.printStackTrace();
        System.exit(1);

    }

    boatArray1 = new Boat[boatNames.length];

    if(boatNames.length > 0){

        try(BufferedWriter fileOut = Files.newBufferedWriter(outPath, Charset.forName("UTF-16"))){

            for(j = 0 ; j < boatNames.length ; j++){

                String delimiters = "[. ,]";
                int limit = -1;

                String[]tokens = boatNames[j].split(delimiters, limit);

                for(k = 0 ; k < tokens.length ; ++k){

                    firstChar = tokens[k].charAt(0);
                    firstChar = Character.toUpperCase(firstChar);
                    char[] tokenArray = tokens[k].toCharArray();                            
                    String text = new String(tokenArray, 1, (tokenArray.length - 1) );                          
                    tokens[k] = firstChar + text;                   
                    result = result + tokens[k] + " ";

                    if(k != tokens.length - 1){

                        continue;

                    }else{

                        result = result.trim();
                        boatNames[k] = result;
                        result = " ";

                    }
                }       

                firstLetter = boatNames[j].charAt(0);

                if((firstLetter == 'B') || (firstLetter == 'C') || (firstLetter == 'N')){

                    boatArray1[j] = new RaceBoat();


                }else{

                    boatArray1[j] = new SailBoat();

                }

                boatArray1[j].christenBoat(boatNames[j]);               

            }

            System.out.println("\n");

            for(l = 0 ; l < boatNames.length ; ++l){            

                secondLetter = Character.toUpperCase(boatNames[l].charAt(1));

                if((secondLetter == 'A') || (secondLetter == 'E')){

                    if(l > 0){

                        fileOut.newLine();
                    }                       
                    fileOut.write(boatArray1[l].goFast());

                }else{

                    if(l > 0){

                        fileOut.newLine();
                    }               
                    fileOut.write(boatArray1[l].goSlow());

                }           

                fileOut.newLine();
                fileOut.write(boatArray1[l].launchBoat());
                fileOut.newLine();
                fileOut.write(boatArray1[l].whatIsBoatState());
                fileOut.newLine();

            }

            boatArray2 = new Boat[3];

            boatArray2[0] = new SailBoat();
            boatArray2[1] = new RaceBoat("Endurance", true);
            boatArray2[2] = new RaceBoat(false);

            for(m = 0 ; m < boatArray2.length ; ++m){

                fileOut.newLine();
                fileOut.write(boatArray2[m].toString());
                fileOut.newLine();
                fileOut.write(boatArray2[m].launchBoat());
                fileOut.newLine();
                fileOut.write(boatArray2[m].whatIsBoatState());
                fileOut.newLine();

            }

            fileOut.newLine();
            fileOut.write("There are " + Boat.boatCount + " boats in the fleet this morning.");


        }catch(IOException e){

        System.err.println("Error writing outPath: " + outPath);
        e.printStackTrace();

        }

    }else{

        System.out.println("\n\n\nArgh!... you forgot to enter ship names scalawag!" +
            "\n\n\n\tPlease try again!");

    }

    System.out.println("\nThe Fleet Registry is completed, press ENTER to continue.\n");

    try{

        System.in.read();

    } catch(IOException e){

        return;
    }
}
}

谢谢大家,我输入了以下内容:

    if(boatNames != null){

        boatArray1 = new Boat[boatNames.length];

        if(boatNames.length > 0){

            try(BufferedWriter fileOut = Files.newBufferedWriter(outPath, Charset.forName("UTF-16"))){

                for(j = 0 ; j < boatNames.length ; j++){

                    String delimiters = "[. ,]";
                    int limit = -1;

                    String[]tokens = boatNames[j].split(delimiters, limit);

                    for(k = 0 ; k < tokens.length ; ++k){

                        firstChar = tokens[k].charAt(0);
                        firstChar = Character.toUpperCase(firstChar);
                        char[] tokenArray = tokens[k].toCharArray();                            
                        String text = new String(tokenArray, 1, (tokenArray.length - 1) );                          
                        tokens[k] = firstChar + text;                   
                        result = result + tokens[k] + " ";

                        if(k != tokens.length - 1){

                            continue;

                        }else{

                            result = result.trim();
                            boatNames[k] = result;
                            result = " ";

                        }
                    }       

                    firstLetter = boatNames[j].charAt(0);

                    if((firstLetter == 'B') || (firstLetter == 'C') || (firstLetter == 'N')){

                        boatArray1[j] = new RaceBoat();


                    }else{

                        boatArray1[j] = new SailBoat();

                    }

                    boatArray1[j].christenBoat(boatNames[j]);               

                }

                System.out.println("\n");

                for(l = 0 ; l < boatNames.length ; ++l){            

                    secondLetter = Character.toUpperCase(boatNames[l].charAt(1));

                    if((secondLetter == 'A') || (secondLetter == 'E')){

                        if(l > 0){

                            fileOut.newLine();
                        }

                        fileOut.write(boatArray1[l].goFast());

                    }else{

                        if(l > 0){

                            fileOut.newLine();
                        }

                        fileOut.write(boatArray1[l].goSlow());

                    }           

                    fileOut.newLine();
                    fileOut.write(boatArray1[l].launchBoat());
                    fileOut.newLine();
                    fileOut.write(boatArray1[l].whatIsBoatState());
                    fileOut.newLine();

                }

                boatArray2 = new Boat[3];

                boatArray2[0] = new SailBoat();
                boatArray2[1] = new RaceBoat("Endurance", true);
                boatArray2[2] = new RaceBoat(false);

                for(m = 0 ; m < boatArray2.length ; ++m){

                    fileOut.newLine();
                    fileOut.write(boatArray2[m].toString());
                    fileOut.newLine();
                    fileOut.write(boatArray2[m].launchBoat());
                    fileOut.newLine();
                    fileOut.write(boatArray2[m].whatIsBoatState());
                    fileOut.newLine();

                }

                fileOut.newLine();
                fileOut.write("There are " + Boat.boatCount + " boats in the fleet this morning.");


            }catch(IOException e){

            System.err.println("Error writing outPath: " + outPath);
            e.printStackTrace();

            }

        }else{

            System.out.println("\n\n\nArgh!... you forgot to enter ship names scalawag!" +
                "\n\n\n\tPlease try again!");

        }

        System.out.println("\nThe Fleet Registry is completed, press ENTER to continue.\n");

        try{

            System.in.read();

        } catch(IOException e){

            return;
        }
    }

现在我收到以下错误:

C:\Documents and Settings\Joe King\My Documents\418.85A Java\Project5>java Project5
Exception in thread "main" java.lang.NullPointerException
       at Project5.main(Project5.java:424)

这对我来说没有意义,为了到达第424行,boatNames数组不能为null,因为在第424行之前多次使用了boatNames的长度。我错过了什么?

由于

4 个答案:

答案 0 :(得分:9)

变量 try/catch之外,否则编译错误会有所不同。问题是初始化位于try块内,因此try之后的代码无法确定变量是否已初始化。

有两种方法可以解决这个问题:

  1. 声明变量时初始化变量。只需使用它就足够了:

    String[] boatNames = null;

  2. 移动try块内使用该变量的所有代码。这通常是一个很好的策略,但前提是你的方法很小。在你的情况下,我不建议这样做,因为你的方法太长了。现在,如果您可以将代码分解为更短的方法,那么将变量的范围限制为单个try块将是有道理的。

答案 1 :(得分:4)

在try / catch块之前,像这样初始化数组:

String[] boatNames = null;

答案 2 :(得分:4)

您已在try block

之外声明了数组
String[] boatNames;

它将在第一个试块

下初始化
boatNames = new String[totalRead];

问题在这里boatArray1 = new Boat[boatNames.length];

原因是,您的编译器无法知道boatNames初始化是否成功,因为可能存在异常并且初始化将失败。

作为声明的一部分,您可以这样做:

String[] boatNames = null; // This will fix your immediate problem 

但这样做可能会导致NullPointerException,因为您的文件读取可能会失败。

要解决此问题,请在使用之前对阵列进行空检查。

if(boatNames == null){
   // I am not going to go further or will take corrective measures here
} 

答案 3 :(得分:0)

这里的编译器考虑了在boatNames初始化之前可能在try块中引发异常的可能性,因此它给出了编译器错误might not have been initialized可能在这里很重要!

这里的理想解决方案是调整代码结构并放入

boatArray1 = new Boat[boatNames.length];

在同一个试块中!