在String.split()和null值之后进行解析

时间:2013-11-04 21:10:24

标签: java

我试图在拆分为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();
    }
}

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

3 个答案:

答案 0 :(得分: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();
    }

}

答案 1 :(得分:0)

您忘记初始化矢量变量。

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

因此在执行时会抛出NullPointerException

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

如果您要解决此问题,我认为您要打印vectorAvectorB的内容,请执行以下操作:

System.out.println(Arrays.toString(vectorA));
System.out.println(Arrays.toString(vectorB));

答案 2 :(得分:0)

vectorA = new int[valueSplittedA.length];
for(int i = 0; i<valueSplittedA.length; i++){
    String temp = valueSplittedA[i];
    vectorA[i] = Integer.parseInt(temp);
}