我有一个文件,内容如下:
J1 0 90 "7,27,73,86"
J2 1 39 "12"
J3 2 195 "11,31,73,94,120,134,183"
我将第四列数字存储为字符串
Scanner input = new Scanner( new File( "projectData.txt" ) );
while ( input.hasNext() )
{
job = input.next();//
arrival = input.nextInt();//
cpu = input.nextInt();
fault = input.next();
jobs[i] = new MyJobs( job, arrival, cpu, fault );//stores four local variables in array
i++;//increments I
如何解析字符串以将它们存储为整数,以便稍后将它们与我的 cpu 值进行比较?
最佳答案
基本方法是使用 String.substring()
删除双引号,然后使用 String.split()
将逗号插入 String[]
。从这里您就知道 int[]
需要有多大,因此只需迭代 String[]
并将每个元素转换为 int
.
public static void main(String[] args) throws Exception {
String fault = "\"11,31,73,94,120,134,183\"";
String[] pieces = fault.substring(1, fault.length() - 1).split(",");
int[] faultNumbers = new int[pieces.length];
for (int i = 0; i < faultNumbers.length; i++) {
faultNumbers[i] = Integer.parseInt(pieces[i]);
}
System.out.println(Arrays.toString(faultNumbers));
}
结果:
[11, 31, 73, 94, 120, 134, 183]
Java 8 流
为了使用流构建 @alfasin 答案,可以缩短基本方法。
public static void main(String[] args) throws Exception {
String fault = "\"11,31,73,94,120,134,183\"";
String[] pieces = fault.substring(1, fault.length() - 1).split(",");
// This does the job of the for loop in the basic approach
int[] faultNumbers = Arrays.stream(pieces)
.mapToInt(Integer::parseInt)
.toArray();
System.out.println(Arrays.toString(faultNumbers));
}
关于Java 我该如何解析这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31768087/