gpt4 book ai didi

java - String.split() 和空值之后的解析

转载 作者:行者123 更新时间:2023-12-01 13:53:33 25 4
gpt4 key购买 nike

我正在尝试将字符串拆分为 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();
}
}

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

最佳答案

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

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();
}

}

关于java - String.split() 和空值之后的解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19777175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com