gpt4 book ai didi

java - 有没有办法扫描 ArrayList 中的索引? .nextint .nextln 等?

转载 作者:行者123 更新时间:2023-11-30 04:13:13 25 4
gpt4 key购买 nike

我有一个名为 data 的 ArrayList。

数据中的每个索引都包含一行单词和数字。例如:

data(0) contains: Bob Sinclair, BS776, 87.5, 23.4, 20.1, 50.2

data(1) contains: Paul Paulson, PP009, 98.3, 12.6, 34.0, 22.5

...再加上 8 个

有没有办法可以将每个对象分成 6 个对象(姓名、学号、Score1、Score2、Score3、Score4)?

之后我需要将分数加在一起以获得总分,但我并不是在这部分寻求帮助,只是提到它,因为数字不能是字符串,因为它们需要相加(或者它们可以是字符串,/耸肩,我是个菜鸟)。

最佳答案

是的,剥猫皮的方法不止一种:

第一个:String.split()

String[] parts = inputString.split(','); //split the input
String name = parts[0]; //get first part.
double[] scores = new double[4]; //create array for doubles
for(int i=0; i<4; i++) { //fill array of doubles --> array index checking might be needed!
scores[i]=Double.parseDouble(scores[i+2]);
}

但是,由于这涉及 float ,您应该阅读 What Every Computer Scientist Should Know About Floating-Point Arithmetic为什么它们可以显示有趣的结果...或者,您可以使用 BigDecimals

BigDecimal exactResult = BigDecimal.valueOf(scores[i+2]);

第二种可能性:Scanner

Scanner s = new Scanner(inputString);
s.useDelimiter(",");
String name = s.next();
double[] scores = new double[4]; //create array for doubles
String someCode = s.next();
for(int i=0; i<4; i++) { //fill array of doubles
scores[i]=Double.parseDouble(s.next()); //null check might be needed!
}

第三:使用模式

//this pattern is very ugly (unsacalable, unmaintainable), but should work for now as poc...
Pattern p = Pattern.compile("([^,]*),\\s*([^,]*),\\s*([^,]*),\\s*([^,]*),\\s*([^,]*),\\s*([^,]*)");
Matcher m = p.matcher(inputString);
if(matcher.matches()) {
String name = group(1);
String someCode = group(2);
double[] scores = new double[4]; //create array for doubles
for(int i=0; i<4; i++) { //fill array of doubles
scores[i]=Double.parseDouble(s.group(i+3)); //null check might be needed!
}
}

关于java - 有没有办法扫描 ArrayList 中的索引? .nextint .nextln 等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19093594/

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