0

配列 token[] がヌル値を読み取らないようにするには、どのようにコーディングする必要がありますか? コードは次のとおりです。

String[] token = new String[0];
String opcode;
String strLine="";
String str="";
    try{
        // Open and read the file
        FileInputStream fstream = new FileInputStream("a.txt");

        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

        //Read file line by line and storing data in the form of tokens
        if((strLine = br.readLine()) != null){

                token = strLine.split(" |,");//// split w.r.t spaces and ,  

  // what do I need to code, so that token[] doesnt take null values

            }
            }
        in.close();//Close the input stream
    }
4

3 に答える 3

0

はい、null配列の要素に値を設定できます。トークンでnull値を防止する場合は、割り当ての前に最初に確認する必要があります。ただし、コードでは、token配列はインデックス 0 で 1 つの要素のみを受け入れます。多くの要素を設定する必要がある場合は、使用を検討してListください。そして、あなたが割り当てたものは、によって返される他の配列によって上書きされsplitます.

String[] token = strLine.split(" |,");
if(token!= null && token.lingth >0){

  // use the array
于 2013-03-29T17:58:02.577 に答える
0

これを処理するオブジェクト指向の方法は、token配列をカプセル化する新しいクラスを作成することです。このクラスに要素を設定および取得する方法を提供します。null が渡されると、set メソッドは例外をスローします。

public void setElement(int index, String element) {
    if (element == null)
        throw new IllegalArgumentException();
    //...
}

あなたの場合、token配列を作成していないので、そこから新しいクラスを作成します:

for each t in token
   myEncapsulation.setElement(loopCount, t);

もちろん、これは疑似コードです。

于 2013-03-29T18:01:16.137 に答える
0

Disclaimer: I'm not really sure what your question is about, maybe you should add some details.

Anyway, from the returns section of split method javadoc:

Returns:

the array of strings computed by splitting this string around matches of the given regular expression

Here is a link: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String, int)

So the split method always returns a String array. If the passed regexp doesn't match it will return a String array with just one element: the original String.

This line:

if(strLine.split(" |,")!=null){

Should become like this:

String[] splittedStrLine = strLine.split(" |,");
if(splittedStrLine.length > 1) {

Hope this helps

于 2013-03-29T18:10:58.290 に答える