0

我试图在拆分为int后解析字符串。我在打印时收到空值。

public class Usage {
    public int[] vectorA, vectorB; public String value; 
    public String[] valueSplittedA, valueSplittedB;

    public void scan(){
        Scanner sc = new Scanner(System.in);
        value = sc.nextLine();
    }

    public void scanLine(){ //Get users values for vectors
        System.out.println("Enter the first Vector\n");
        scan();
        valueSplittedA = value.split(" ");
        System.out.println("Enter the second Vector\n");
        scan();
        valueSplittedB = value.split(" ");
        for(int i = 0; i<valueSplittedA.length; i++){
            String temp = valueSplittedA[i];
            vectorA[i] = Integer.parseInt(temp);
        }
        for(int i = 0; i<valueSplittedB.length; i++){
            String temp = valueSplittedB[i];
            vectorB[i] = Integer.parseInt(temp);
        }
        System.out.println(vectorA);
        System.out.println(vectorB);
    }

}

主要方法:

public class Five {
    public static void main(String[] args) {
        Usage usage = new Usage();
        usage.scanLine();
    }
}

两个向量的打印都显示为空。怎么了?

4

3 回答 3

1

你忘了初始化你的数组。这是完整的工作程序。

import java.util.Scanner;
import cern.colt.Arrays;

public class Usage {
    public int[] vectorA, vectorB; public String value; 
    public String[] valueSplittedA, valueSplittedB;

    public void scan(){
        Scanner sc = new Scanner(System.in);
        value = sc.nextLine();
    }

    public void scanLine(){ //Get users values for vectors
        System.out.println("Enter the first Vector\n");
        scan();
        valueSplittedA = value.split(" ");
        vectorA = new int[valueSplittedA.length];
        System.out.println("Enter the second Vector\n");
        scan();
        valueSplittedB = value.split(" ");
        vectorB = new int[valueSplittedB.length];
        for(int i = 0; i<valueSplittedA.length; i++){
            String temp = valueSplittedA[i];
            vectorA[i] = Integer.parseInt(temp);
       }
        for(int i = 0; i<valueSplittedB.length; i++){
            String temp = valueSplittedB[i];
            vectorB[i] = Integer.parseInt(temp);
        }
        System.out.println(Arrays.toString(vectorA));
        System.out.println(Arrays.toString(vectorB));
    }

    public static void main(String[] args){
        Usage u = new Usage();
        u.scanLine();
    }

}

于 2013-11-04T21:17:36.760 回答
0

您忘记初始化向量变量。

public int[] vectorA, vectorB; <-- declared but not initialized

因此它NullPointerException在做时抛出一个:

vectorA[i] = Integer.parseInt(temp);

当你解决这个问题时,我假设你想要打印的内容,vectorA所以vectorB这样做:

System.out.println(Arrays.toString(vectorA));
System.out.println(Arrays.toString(vectorB));
于 2013-11-04T21:12:39.557 回答
0
vectorA = new int[valueSplittedA.length];
for(int i = 0; i<valueSplittedA.length; i++){
    String temp = valueSplittedA[i];
    vectorA[i] = Integer.parseInt(temp);
}
于 2013-11-04T21:16:36.757 回答