1

私はしばらくの間このコードを蹴っていましたが、一般的な問題が何であるかを知っていると思います。それを修正する方法がわかりません。次のエラーが発生します。

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に到達するために、これは私には意味がありません。行424の前にboatNamesの長さが数回使用されたため、boatNames配列をnullにすることはできません。何が欠けていますか?

ありがとう

4

4 に答える 4

9

変数の範囲外ですtry/catch。それ以外の場合、コンパイル エラーは異なります。問題は、初期化tryブロック内にあるため、 の後のコードでtry変数が初期化されたことを確認できないことです。

これに対処するには、次の 2 つの方法があります。

  1. 宣言時に変数を初期化します。これを使用するだけで十分です:

    String[] boatNames = null;

  2. tryブロック内の変数を使用するすべてのコードを移動します。多くの場合、これは良い戦略ですが、メソッドが小さい場合に限ります。あなたの場合、メソッドが長すぎるため、これはお勧めしません。ここで、コードを短いメソッドに分割できれば、変数のスコープを 1 つのtryブロックに制限することは理にかなっています。

于 2012-06-11T04:18:05.083 に答える
4

try/catch ブロックの前に、次のように配列を初期化します。

String[] boatNames = null;
于 2012-06-11T04:19:53.063 に答える
4

try ブロックの外で配列を宣言しました

String[] boatNames;

最初の試行ブロックの下で初期化されます

boatNames = new String[totalRead];

問題はこちらboatArray1 = new Boat[boatNames.length];

boatNames例外が発生して初期化が失敗する可能性があるため、コンパイラは初期化が成功するかどうかを知る方法がありません。

宣言の一部として、次のことができます。

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

ただし、これを行うとNullPointerException、ファイルの読み取りが失敗する可能性があるため、次のようになる可能性があります。

これを解決するには、配列を使用する前に null チェックを行います。

if(boatNames == null){
   // I am not going to go further or will take corrective measures here
} 
于 2012-06-11T04:20:19.303 に答える
0

ここでのコンパイラは、が初期化される前であっても try ブロックで例外が発生する可能性を考慮しているboatNamesため、コンパイラ エラーが発生しますmight not have been initialized。ここは力が大事!

ここでの理想的な解決策は、コード構造を微調整して配置することです

boatArray1 = new Boat[boatNames.length];

同じtryブロックで!

于 2012-06-11T04:26:30.787 に答える